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:com.palantir.paxos.PaxosStateLogImpl.java

private static final Comparator<File> nameAsLongComparator() {
    return new Comparator<File>() {
        @Override/*from w ww  .j  av  a 2s. co  m*/
        public int compare(File f1, File f2) {
            Long s1 = getSeqFromFilename(f1);
            Long s2 = getSeqFromFilename(f2);
            return s1.compareTo(s2);
        }
    };
}

From source file:Main.java

/**
 * Utility method to sort two related arrays - that is, two arrays where the elements are related to each other
 * by their position in the array. i.e. firstArray[0] is related to secondArray[0], firstArray[1] is related to
 * secondArray[1], and so on. The first array is sorted based on its implementation of Comparable, and the 2nd
 * array is sorted by it's related item in the first array, so that the same elements are still related to each
 * other after the sort// w  w  w.  j a  v a2 s .com
 * @param firstArray The first array, which contains the values to sort
 * @param secondArray The second array, which will be sorted based on the values in the first array
 * @param <A> The type of element in the first array
 * @param <B> the type of element in the second array
 */
public static <A extends Comparable<A>, B> void sortTwoArrays(A[] firstArray, B[] secondArray) {
    if (firstArray.length != secondArray.length) {
        throw new RuntimeException("Both arrays must be of the same length");
    }

    class element {
        public A first;
        public B second;
    }

    element[] elements = new element[firstArray.length];

    Arrays.sort(elements, new Comparator<element>() {
        public int compare(element a, element b) {
            return a.first.compareTo(b.first);
        }
    });

    for (int i = 0; i < elements.length; i++) {
        firstArray[i] = elements[i].first;
        secondArray[i] = elements[i].second;
    }
}

From source file:com.github.tomakehurst.wiremock.matching.MultiValuePattern.java

private static MatchResult getBestMatch(final StringValuePattern valuePattern, List<String> values) {
    List<MatchResult> allResults = Lists.transform(values, new Function<String, MatchResult>() {
        public MatchResult apply(String input) {
            return valuePattern.match(input);
        }/*from  w  ww.  j av  a  2  s.  c  om*/
    });

    return min(allResults, new Comparator<MatchResult>() {
        public int compare(MatchResult o1, MatchResult o2) {
            return new Double(o1.getDistance()).compareTo(o2.getDistance());
        }
    });
}

From source file:com.linkedin.pinot.common.restlet.PinotRestletApplication.java

protected void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) {
    TreeSet<String> pathsOrderedByLength = new TreeSet<String>(
            ComparatorUtils.chainedComparator(new Comparator<String>() {

                @Override//  www.  j  ava2  s.c om
                public int compare(String left, String right) {
                    int leftLength = left.length();
                    int rightLength = right.length();
                    return leftLength < rightLength ? -1 : (leftLength == rightLength ? 0 : 1);
                }
            }, ComparatorUtils.NATURAL_COMPARATOR));

    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotationInstance = method.getAnnotation(Paths.class);
        if (annotationInstance != null) {
            pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value()));
        }
    }

    for (String routePath : pathsOrderedByLength) {
        LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName());
        attachRoute(router, routePath, clazz);
    }
}

From source file:fi.nls.fileservice.web.admin.controller.DatasetAdminController.java

@RequestMapping(value = "/tuotteet", method = RequestMethod.GET)
public String datasetList(HttpServletRequest request, Model model) {
    List<Dataset> datasets = datasetService.getAllDatasets();

    // sort alphabetically by title
    Collections.sort(datasets, new Comparator<Dataset>() {

        @Override//from w w  w . j  a v a 2s  . com
        public int compare(Dataset d1, Dataset d2) {
            String d1Title = d1.getTranslatedTitles().get("fi");
            String d2Title = d2.getTranslatedTitles().get("fi");
            if (d1Title != null && d2Title != null) {
                return d1Title.compareTo(d2Title);
            }

            return 0;
        }

    });

    model.addAttribute("datasets", datasets); // auto gen would give JCRNodeDatasetList
    return "admin/datasets";
}

From source file:com.github.fge.jsonschema.keyword.digest.draftv4.DraftV4DependenciesDigester.java

private static JsonNode sortedSet(final JsonNode node) {
    final List<JsonNode> list = Lists.newArrayList(node);

    Collections.sort(list, new Comparator<JsonNode>() {
        @Override//from  www. j a  v  a2  s.  c o m
        public int compare(final JsonNode o1, final JsonNode o2) {
            return o1.textValue().compareTo(o2.textValue());
        }
    });

    final ArrayNode ret = FACTORY.arrayNode();
    ret.addAll(list);
    return ret;
}

From source file:net.big_oh.common.flatfile.FlatFileRecordBuilder.java

/**
 * Builds a single record (i.e. line) in the flat file using the collection
 * of {@link FlatFileRecordField} objects.
 * /*from   w  ww.ja v  a 2 s.  c  om*/
 * @param fieldsForRecord
 *            The FlatFileRecordField objects used to construct a single
 *            record for the flat file.
 * @param fieldDelimiter
 *            An optional character that can be placed between fields in the
 *            flat file record.
 * @param interFieldPadChar
 *            The character used to fill any spaces that do not correspond
 *            to a field in the flat file record.
 * @return A single record (i.e. line) to be included in a flat file.
 * @throws IllegalArgumentException
 *             Thrown if the Collection of FlatFileRecordField objects
 *             overlap.
 */
public static String buildFlatFileRecord(Collection<FlatFileRecordField> fieldsForRecord, String fieldDelimiter,
        char interFieldPadChar) throws IllegalArgumentException {

    StringBuffer recordContent = new StringBuffer();

    List<FlatFileRecordField> sortedFieldsForRecord = new ArrayList<FlatFileRecordField>(fieldsForRecord);
    Collections.sort(sortedFieldsForRecord, new Comparator<FlatFileRecordField>() {
        public int compare(FlatFileRecordField o1, FlatFileRecordField o2) {
            return new Integer(o1.getFieldFormat().getFieldStartPosition())
                    .compareTo(new Integer(o2.getFieldFormat().getFieldStartPosition()));
        }
    });

    int lastPositionPopulated = 0;
    for (FlatFileRecordField recordField : sortedFieldsForRecord) {
        FlatFileFieldFormat fieldFormat = recordField.getFieldFormat();

        // add the field delimiter before all fields but the first
        if (fieldDelimiter != null && lastPositionPopulated > 0) {
            recordContent.append(fieldDelimiter);
        }

        // check to see whether we've encountered two overlapping fields
        if (lastPositionPopulated >= fieldFormat.getFieldStartPosition()) {
            throw new IllegalArgumentException(
                    "Field " + fieldFormat.toString() + " overlaps with another field.  This is not allowed.");
        }

        // add whitespace as needed to fill gap between consecutive fields
        while (lastPositionPopulated < fieldFormat.getFieldStartPosition() - 1) {
            recordContent.append(interFieldPadChar);
            lastPositionPopulated++;
        }

        int fieldLength = fieldFormat.getFieldLength();

        String fieldValue = recordField.getFieldValue();

        // abbreviate values that are too long
        if (fieldValue.length() > fieldLength) {
            fieldValue = fieldValue.substring(0, fieldLength);
        }

        // pad values that are too short
        if (fieldFormat.getPaddingType().equals(FlatFileFieldPaddingType.PADDING_ON_LEFT)) {
            fieldValue = StringUtils.leftPad(fieldValue, fieldLength, fieldFormat.getIntraFieldPaddingChar());
        } else if (fieldFormat.getPaddingType().equals(FlatFileFieldPaddingType.PADDING_ON_RIGHT)) {
            fieldValue = StringUtils.rightPad(fieldValue, fieldLength, fieldFormat.getIntraFieldPaddingChar());
        }

        // add the field value now that it is the proper size for the field
        recordContent.append(fieldValue);
        lastPositionPopulated += fieldValue.length();

    }

    return recordContent.toString();

}

From source file:org.jasig.portlet.survey.service.report.SurveyReportMapperImpl.java

@PostConstruct
public void init() {
    Map<String, ISurveyReportGenerator> beans = applicationContext.getBeansOfType(ISurveyReportGenerator.class);
    generators.addAll(beans.values());/*from w w  w  .ja  v  a 2s .  c o  m*/
    Collections.sort(generators, new Comparator<ISurveyReportGenerator>() {
        @Override
        public int compare(ISurveyReportGenerator g1, ISurveyReportGenerator g2) {
            return g1.getPriority() - g2.getPriority();
        }
    });
}

From source file:net.firejack.platform.service.registry.helper.PackageVersionHelper.java

public static FileInfo[] sortingByName(FileInfo[] files, boolean desc) {
    Arrays.sort(files, new Comparator() {
        public int compare(final Object o1, final Object o2) {
            String s1 = ((FileInfo) o1).getFilename().toLowerCase();
            String s2 = ((FileInfo) o2).getFilename().toLowerCase();
            return s1.compareTo(s2);
        }// w w w  .j a v a2s .com
    });
    if (desc) {
        org.apache.commons.lang.ArrayUtils.reverse(files);
    }
    return files;
}

From source file:springfox.documentation.spi.service.contexts.Orderings.java

public static Comparator<ApiDescription> apiPathCompatator() {
    return new Comparator<ApiDescription>() {
        @Override/*from www  .  j a va  2s  .  c  o  m*/
        public int compare(ApiDescription first, ApiDescription second) {
            return first.getPath().compareTo(second.getPath());
        }
    };
}