Example usage for java.util Comparator Comparator

List of usage examples for java.util Comparator Comparator

Introduction

In this page you can find the example usage for java.util Comparator Comparator.

Prototype

Comparator

Source Link

Usage

From source file:net.sourceforge.fenixedu.presentationTier.validator.form.ValidateCompareTwoFields.java

/**
 * Compares two fields and checks if second field >= first field
 * /*from   ww w  .j  a  va  2  s.co  m*/
 * @param bean
 * @param va
 * @param field
 * @param errors
 * @param request
 * @param application
 * @return
 */
public static boolean validateGreaterThanOrEqual(Object bean, ValidatorAction va, Field field,
        ActionMessages errors, HttpServletRequest request, ServletContext application) {
    return validate(bean, va, field, errors, request, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            Double d1 = (Double) o1;
            Double d2 = (Double) o2;

            int result = d1.compareTo(d2);
            if (result <= 0) {
                result = VALUE;
            }
            return result;
        }
    });
}

From source file:com.hmsinc.epicenter.webapp.dto.DataTypeDTO.java

public DataTypeDTO(final DataType dataType) {

    this.id = dataType.getId();
    this.name = dataType.getName();
    classifiers.add(new KeyValueDTO("TOTAL", "Total Counts"));

    final List<Classifier> ccs = new ArrayList<Classifier>();
    for (ClassificationTarget target : dataType.getTargets()) {
        ccs.add(target.getClassifier());
    }/*from  ww  w  .j a  v a  2 s .c om*/

    Collections.sort(ccs, new Comparator<Classifier>() {
        public int compare(Classifier o1, Classifier o2) {
            return new CompareToBuilder().append(o1.isBeta(), o2.isBeta()).append(o1.getName(), o2.getName())
                    .toComparison();
        }
    });

    for (Classifier cc : ccs) {

        if (cc.isEnabled()) {

            classifiers.add(new KeyValueDTO(cc.getId().toString(), cc.getName(),
                    cc.getName() + (cc.isBeta() ? " (BETA)" : "")));

            final Set<Classification> cls = cc.getClassifications();
            categories.put(cc.getId(), new TreeSet<KeyValueDTO>());
            for (Classification c : cls) {
                categories.get(cc.getId()).add(new KeyValueDTO(c.getId().toString(), c.getCategory()));
            }

            if (!cc.isBeta()) {
                allClassifiersBeta = false;
            }
        }
    }
}

From source file:com.alibaba.cobar.manager.util.CobarStringUtil.java

/**
 * e.g. {"mysql_1","mysql_2","mysql_3","mysql_5"} will return
 * {"mysql_$1-3","mysql_5"}<br/>/*from  ww  w.ja v a  2s.co  m*/
 * only merge last number
 */
public static List<String> mergeListedString(String[] input) {
    if (input == null || input.length < 1)
        return Collections.emptyList();
    if (input.length == 1) {
        List<String> rst = new ArrayList<String>(1);
        rst.add(input[0]);
        return rst;
    }
    List<String> list = new ArrayList<String>(input.length);
    for (String str : input)
        list.add(str);
    Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (StringUtils.equals(o1, o2))
                return 0;
            if (o1.length() == o2.length())
                return o1.compareTo(o2);
            return o1.length() < o2.length() ? -1 : 1;
        }
    });

    List<String> rst = new ArrayList<String>();

    String prefix = null;
    Integer from = null;
    Integer to = null;
    String last = list.get(0);
    for (int i = 1; i < list.size(); ++i) {
        String cur = list.get(i);
        if (StringUtils.equals(last, cur))
            continue;
        int commonInd = indexOfLastEqualCharacter(last, cur);

        boolean isCon = false;

        if (commonInd >= 0) {
            String suffixLast = last.substring(1 + commonInd);
            String suffixCur = cur.substring(1 + commonInd);
            try {
                int il = Integer.parseInt(suffixLast);
                int ic = Integer.parseInt(suffixCur);
                if (ic - il == 1)
                    isCon = true;
            } catch (Exception e) {
            }
        }

        if (isCon) {
            if (prefix == null)
                prefix = last.substring(0, commonInd + 1);
            if (from == null)
                from = Integer.parseInt(last.substring(commonInd + 1));
            to = Integer.parseInt(cur.substring(commonInd + 1));
        } else if (prefix != null) {
            rst.add(new StringBuilder(prefix).append('$').append(from).append('-').append(to).toString());
            prefix = null;
            from = to = null;
        } else {
            rst.add(last);
        }
        last = cur;
    }

    if (prefix != null) {
        rst.add(new StringBuilder(prefix).append('$').append(from).append('-').append(to).toString());
        prefix = null;
        from = to = null;
    } else {
        rst.add(last);
    }

    return rst;
}

From source file:com.myee.tarot.core.web.form.entity.FieldGroup.java

public Set<Field> getFields() {
    List<Field> myFields = new ArrayList<Field>();
    myFields.addAll(fields);//from w ww.j a  v a  2 s. c om
    Collections.sort(myFields, new Comparator<Field>() {
        @Override
        public int compare(Field o1, Field o2) {
            return new CompareToBuilder().append(o1.getOrder(), o2.getOrder())
                    .append(o1.getFriendlyName(), o2.getFriendlyName()).append(o1.getName(), o2.getName())
                    .toComparison();
        }
    });
    if (!alternateOrderedFields.isEmpty()) {
        List<Field> mapFieldsList = new ArrayList<Field>(alternateOrderedFields);
        Collections.sort(mapFieldsList, new Comparator<Field>() {
            @Override
            public int compare(Field o1, Field o2) {
                return new CompareToBuilder().append(o1.getOrder(), o2.getOrder())
                        .append(o1.getFriendlyName(), o2.getFriendlyName()).append(o1.getName(), o2.getName())
                        .toComparison();
            }
        });
        /*
        alternate ordered fields whose order is less or equal to zero appear first and are
        prepended to the response list in order
         */
        List<Field> smallOrderFields = new ArrayList<Field>();
        for (Field mapField : mapFieldsList) {
            if (mapField.getOrder() <= 0) {
                smallOrderFields.add(mapField);
            }
        }
        myFields.addAll(0, smallOrderFields);
        /*
        Alternate ordered fields (specifically custom fields) have a different ordering rule than regular fields. For example,
        if a user enters 3 for the field order value for a custom field, that custom field should be the third
        on the form. Regular BLC AdminPresentation fields tends to have orders like 1000, 2000, etc..., so this
        distinction is necessary.
         */
        for (Field mapField : mapFieldsList) {
            if (mapField.getOrder() <= 0) {
                continue;
            }
            if (mapField.getOrder() < myFields.size() + 1) {
                myFields.add(mapField.getOrder() - 1, mapField);
                continue;
            }
            myFields.add(mapField);
        }
    }

    //don't allow any modification of the fields
    return Collections.unmodifiableSet(new LinkedHashSet<Field>(myFields));
}

From source file:org.eclipse.virgo.ide.runtime.internal.core.DefaultServerDeployer.java

/**
 * {@inheritDoc}//from  w w  w  .  j ava 2 s  .  c  om
 */
public void deploy(IModule... modules) {
    List<IModule> orderedModules = Arrays.asList(modules);

    // make sure we honor the user configured order
    final List<String> orderedArtefacts = getArtefactOrder();

    // sort the modules according the order defined in the server configuration
    Collections.sort(orderedModules, new Comparator<IModule>() {

        public int compare(IModule o1, IModule o2) {
            Integer m1 = (orderedArtefacts.contains(o1.getId()) ? orderedArtefacts.indexOf(o1.getId())
                    : Integer.MAX_VALUE);
            Integer m2 = (orderedArtefacts.contains(o2.getId()) ? orderedArtefacts.indexOf(o2.getId())
                    : Integer.MAX_VALUE);
            return m1.compareTo(m2);
        }
    });

    for (IModule module : orderedModules) {
        DeploymentIdentity identity = executeDeployerCommand(getServerDeployCommand(module));
        if (behaviour instanceof ServerBehaviour) {
            ((ServerBehaviour) behaviour).tail(identity);
        }
        behaviour.onModulePublishStateChange(new IModule[] { module }, IServer.PUBLISH_STATE_NONE);
        // if (identity != null) {
        // behaviour.onModuleStateChange(new IModule[] { module }, IServer.STATE_STARTED);
        // }
        // else {
        // behaviour.onModuleStateChange(new IModule[] { module }, IServer.STATE_STOPPED);
        // }
    }
}

From source file:net.sourceforge.vulcan.spring.jdbc.JdbcSchemaMigrator.java

public void setMigrationScripts(Resource[] migrationScripts) {
    this.migrationScripts = migrationScripts;
    Arrays.sort(this.migrationScripts, new Comparator<Resource>() {
        public int compare(Resource o1, Resource o2) {
            return o1.getFilename().compareTo(o2.getFilename());
        }//w w  w . j  a va2 s . c  o m
    });
}

From source file:com.sketchy.server.action.GetImageFiles.java

@Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {/*www . j av a2  s .c  om*/
        File[] files = HttpServer.IMAGE_UPLOAD_DIRECTORY.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File arg0, String filename) {
                return (StringUtils.endsWithIgnoreCase(filename, ".dat")
                        && (!StringUtils.endsWithIgnoreCase(filename, "rendered.dat")));
            }
        });

        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                if ((f1 == null) || (f2 == null))
                    return 0; // Shouldn't ever be null, but if so if either is null, then just return 0; 
                return f1.getName().compareToIgnoreCase(f2.getName());
            }
        });

        List<Object> rows = new ArrayList<Object>();
        for (File file : files) {

            Map<String, Object> row = new HashMap<String, Object>();
            File dimFile = new File(file.getPath());
            if (dimFile.exists()) {
                String json = FileUtils.readFileToString(dimFile);
                SourceImageAttributes sourceImageAttributes = (SourceImageAttributes) ImageAttributes
                        .fromJson(json);
                row.put("imageSize", Integer.toString(sourceImageAttributes.getWidth()) + " x "
                        + Integer.toString(sourceImageAttributes.getHeight()));
                row.put("imageName", sourceImageAttributes.getImageName());
                row.put("filename", sourceImageAttributes.getImageFilename());
            }

            rows.add(row);
        }

        jsonServletResult.put("rows", rows);
    } catch (Throwable t) {
        jsonServletResult = new JSONServletResult(Status.ERROR, "Error! " + t.getMessage());
    }

    return jsonServletResult;
}

From source file:org.agiso.tempel.core.provider.CoreTemplateProvider.java

@Autowired(required = false)
public void setTemplateProviderElements(List<ITemplateProviderElement> providers) {
    this.elements = new ArrayList<ITemplateProviderElement>(providers);

    Collections.sort(this.elements, new Comparator<ITemplateProviderElement>() {
        @Override/*from   w w  w .  j  a  v  a2 s .  c o m*/
        public int compare(ITemplateProviderElement e1, ITemplateProviderElement e2) {
            int o1 = e1.getOrder(), o2 = e2.getOrder();
            return ((o1 < o2) ? -1 : ((o1 == o2) ? 0 : 1));
        }
    });

    for (ITemplateProviderElement provider : elements) {
        if (coreLogger.isDebugEnabled())
            coreLogger.debug(Logs.LOG_01, ansiString(GREEN, provider.getClass().getSimpleName()),
                    ansiString(GREEN, provider.getOrder()));
    }
}

From source file:net.chrissearle.flickrvote.web.stats.ShowChallengeChartAction.java

public String stats() throws Exception {
    initializeChallengeInfo();// w w w  . j  a  v a  2 s  .  co  m

    ChallengeItem challenge = photographyService.getChallengeImages(tag);

    images = new ArrayList<Image>(challenge.getImages().size());

    for (ImageItem image : challenge.getImages()) {
        final DisplayImage displayImage = new DisplayImage(image);

        images.add(displayImage);

        if (logger.isLoggable(Level.FINE)) {
            logger.info("Saw " + displayImage.toString());
        }
    }

    Collections.sort(images, new Comparator<Image>() {
        public int compare(Image o1, Image o2) {
            return o1.getRank().compareTo(o2.getRank());
        }
    });

    if (small) {
        height = (long) (18 * images.size()) + 20;
    } else {
        height = (long) (30 * images.size()) + 140;
    }

    return SUCCESS;
}

From source file:com.tech.utils.CustomCollectionUtil.java

/**
 * Method used to sort map by values//from   w w w .j a v a  2 s.com
 * 
 * @param <K>
 *            Map Key
 * @param <V>
 *            Map Value
 * @param map
 *            Map
 * @return sorted Map
 */
public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator = new Comparator<K>() {
        public int compare(final K k1, final K k2) {
            int compare = map.get(k1).compareTo(map.get(k2));

            if (compare == 0) {
                return 1;
            } else {
                return compare;
            }
        }
    };

    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);

    return sortedByValues;
}