Java Code Examples for java.util.Comparator.comparing()

The following are Jave code examples for showing how to use comparing() of the java.util.Comparator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: freecol   File: ClientOptions.java   View Source Code Vote up 6 votes
/**
 * Return the colony comparator identified by type.
 *
 * @param type an {@code int} value
 * @return a {@code Comparator} value
 */
public static Comparator<Colony> getColonyComparator(int type) {
    switch (type) {
    case COLONY_COMPARATOR_AGE:
        return colonyAgeComparator;
    case COLONY_COMPARATOR_POSITION:
        return colonyPositionComparator;
    case COLONY_COMPARATOR_SIZE:
        return colonySizeComparator;
    case COLONY_COMPARATOR_SOL:
        return colonySoLComparator;
    case COLONY_COMPARATOR_NAME:
        if (colonyNameComparator == null) {
            // Can not be done statically, must wait for CLI parsing
            colonyNameComparator = Comparator.comparing(Colony::getName,
                Collator.getInstance(FreeCol.getLocale()));
        }
        return colonyNameComparator;
    default:
        throw new IllegalStateException("Unknown comparator");
    }
}
 
Example 2
Project: buenojo   File: ActivityTraceResource.java   View Source Code Vote up 6 votes
/**
 * PUT  /activityTraces -> Updates an existing activityTrace.
 */
@RequestMapping(value = "/activityTraces/end",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ActivityTrace> endActivityTrace(@Valid @RequestBody ActivityTrace activityTrace) throws URISyntaxException {
    log.debug("REST request to update ActivityTrace : {}", activityTrace);
    if (activityTrace.getId() == null) {
    	return ResponseEntity.badRequest().header("Failure", "no se puede finalizar un registro de actividad que nunca se creó").body(null);
    }
    
    if (activityTrace.getStartDate() == null) {
    	return ResponseEntity.badRequest().header("Failure", "no se puede finalizar un registro de actividad que nunca comenzó").body(null);
    }
    Comparator<ZonedDateTime> comparator = Comparator.comparing(zdt -> ((ZonedDateTime) zdt).truncatedTo(ChronoUnit.SECONDS));
    if (comparator.compare(activityTrace.getStartDate(), activityTrace.getEndDate()) >= 0) {
    	return ResponseEntity.badRequest().header("Failure", "un registro de actividad no puede tener una fecha de finalización anterior a la de comienzo").body(null);
    }
    
    ActivityTrace result = activityTraceRepository.save(activityTrace);
    return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("activityTrace", activityTrace.getId().toString()))
            .body(result);
}
 
Example 3
Project: jdk8u-jdk   File: BasicTest.java   View Source Code Vote up 6 votes
public void testComparatorDefaultMethods() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    // reverseOrder
    assertComparison(cmp.reversed(), people[1], people[0]);
    // thenComparing(Comparator)
    assertComparison(cmp.thenComparing(cmp2), people[0], people[1]);
    assertComparison(cmp.thenComparing(cmp2), people[4], people[0]);
    // thenComparing(Function)
    assertComparison(cmp.thenComparing(People::getLastName), people[0], people[1]);
    assertComparison(cmp.thenComparing(People::getLastName), people[4], people[0]);
    // thenComparing(ToIntFunction)
    assertComparison(cmp.thenComparingInt(People::getAge), people[0], people[1]);
    assertComparison(cmp.thenComparingInt(People::getAge), people[1], people[5]);
    // thenComparing(ToLongFunction)
    assertComparison(cmp.thenComparingLong(People::getAgeAsLong), people[0], people[1]);
    assertComparison(cmp.thenComparingLong(People::getAgeAsLong), people[1], people[5]);
    // thenComparing(ToDoubleFunction)
    assertComparison(cmp.thenComparingDouble(People::getAgeAsDouble), people[0], people[1]);
    assertComparison(cmp.thenComparingDouble(People::getAgeAsDouble), people[1], people[5]);
}
 
Example 4
Project: sonar-css-plugin   File: MultipleLessVariableDeclarationsSameScopeCheck.java   View Source Code Vote up 6 votes
@Override
public void visitStyleSheet(StyleSheetTree tree) {

  Comparator<Usage> byLine = Comparator.comparing(u -> u.identifierTree().value().line());
  Comparator<Usage> byColumn = Comparator.comparing(u -> u.identifierTree().value().column());

  for (Scope scope : getContext().getSymbolModel().getScopes()) {
    for (Symbol symbol : scope.getSymbols(Symbol.Kind.LESS_VARIABLE)) {
      List<Usage> usages = symbol.usages()
        .stream()
        .filter(u -> u.is(Usage.Kind.DECLARATION))
        .sorted(byLine.thenComparing(byColumn))
        .collect(Collectors.toList());

      if (usages.size() > 1) {
        createIssue(usages);
      }
    }
  }
}
 
Example 5
Project: Matcher   File: MatchPaneSrc.java   View Source Code Vote up 5 votes
private Comparator<ClassInstance> getClassComparator() {
	switch (gui.getSortKey()) {
	case Name:
		return Comparator.comparing(MatchPaneSrc::getName);
	case MappedName:
		return Comparator.<ClassInstance, String>comparing(MatchPaneSrc::getMappedName, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(MatchPaneSrc::getName);
	case MatchStatus:
		return clsMatchStatusComparator.thenComparing(MatchPaneSrc::getName);
	}

	throw new IllegalStateException("unhandled sort key: "+gui.getSortKey());
}
 
Example 6
Project: mug   File: BiStream.java   View Source Code Vote up 5 votes
/** Returns a sorted stream based on {@code keyOrdering} and {@code valueOrdering}. */
public BiStream<K, V> sorted(
    Comparator<? super K> keyOrdering, Comparator<? super V> valueOrdering) {
  Comparator<Map.Entry<? extends K, ? extends V>> byKey =
      Comparator.comparing(Map.Entry::getKey, keyOrdering);
  Comparator<Map.Entry<? extends K, ? extends V>> byValue =
      Comparator.comparing(Map.Entry::getValue, valueOrdering);
  return from(underlying.sorted(byKey.thenComparing(byValue)));
}
 
Example 7
Project: buckaroo   File: Levenstein.java   View Source Code Vote up 5 votes
public static <T> Iterable<T> findClosest(final ImmutableList<T> candidates, final T misspelled) {

        final Comparator<Pair<T, Integer>> byDistance = Comparator.comparing(Pair::getValue1);

        return () -> candidates
            .stream()
            .map(c -> Pair.with(c, calcDistance(c.toString(), misspelled.toString())))
            .sorted(byDistance)
            .map(Pair::getValue0)
            .iterator();
    }
 
Example 8
Project: artifactory-resource   File: FileComparator.java   View Source Code Vote up 5 votes
@Override
public int compare(File file1, File file2) {
	Comparator<File> comparator = Comparator.comparing(File::getParentFile);
	comparator = comparator.thenComparingInt(this::byFileType);
	comparator = comparator.thenComparingInt(this::byPomExtension);
	comparator = comparator.thenComparing(this::getFileExtension);
	comparator = comparator.thenComparing(FileComparator::getNameWithoutExtension);
	return comparator.compare(file1, file2);
}
 
Example 9
Project: oryx2   File: Pairs.java   View Source Code Vote up 5 votes
/**
 * @param order whether to sort ascending or descending; {@code null} comes last
 * @param <C> type of first element in {@link Pair}s to be compared
 * @param <D> type of second element in {@link Pair}s to be compared
 * @return an ordering on {@link Pair}s by first element as a {@link Comparator}
 */
public static <C extends Comparable<C>,D> Comparator<Pair<C,D>> orderByFirst(SortOrder order) {
  Comparator<Pair<C,D>> ordering = Comparator.comparing(Pair::getFirst);
  if (order == SortOrder.DESCENDING) {
    ordering = ordering.reversed();
  }
  return Comparator.nullsLast(ordering);
}
 
Example 10
Project: openjdk-jdk10   File: BasicTest.java   View Source Code Vote up 5 votes
public void testMinBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(minBy(cmp).apply(people[0], people[1]), people[0]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(minBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(minBy(cmp).apply(people[0], people[1]), people[1]);
}
 
Example 11
Project: openjdk-jdk10   File: EntryComparators.java   View Source Code Vote up 5 votes
public void testKVComparators() {
    // Comparator<People> cmp = Comparator.naturalOrder(); // Should fail to compiler as People is not comparable
    // We can use simple comparator, but those have been tested above.
    // Thus choose to do compose for some level of interation.
    Comparator<People> cmp1 = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    Comparator<People> cmp = cmp1.thenComparing(cmp2);

    assertPairComparison(people[0], people[0], people[1], people[1],
                     Map.Entry.<People, People>comparingByKey(cmp),
                     Map.Entry.<People, People>comparingByValue(cmp));

}
 
Example 12
Project: ProjectAres   File: ClassMatchModule.java   View Source Code Vote up 5 votes
public ClassMatchModule(Match match, String category, Map<String, PlayerClass> classes, PlayerClass defaultClass) {
    super(match);
    this.category = checkNotNull(category, "category");
    this.classes = checkNotNull(classes, "classes");
    this.defaultClass = checkNotNull(defaultClass, "default class");

    this.classesByName = new TreeSet<>(Comparator.comparing(PlayerClass::getName));
    this.classesByName.addAll(this.classes.values());
}
 
Example 13
Project: OperatieBRP   File: BijhoudingsplanContext.java   View Source Code Vote up 5 votes
/**
 * Constructor voor het bijhoudingsplan.
 * @param bijhoudingVerzoekBericht het bijhouding verzoekbericht
 */
public BijhoudingsplanContext(final BijhoudingVerzoekBericht bijhoudingVerzoekBericht) {
    this.bijhoudingVerzoekBericht = bijhoudingVerzoekBericht;
    this.personenUitHetBijhoudingsplan =
            new TreeSet<>(Comparator.comparing(BijhoudingPersoon::getBsnOrNull, Comparator.nullsFirst(Comparator.naturalOrder())));
    personenDieNietVerwerktMaarWelOntrelateerdZijn = new LinkedHashSet<>();
}
 
Example 14
Project: jdk8u-jdk   File: EntryComparators.java   View Source Code Vote up 5 votes
public void testKVComparators() {
    // Comparator<People> cmp = Comparator.naturalOrder(); // Should fail to compiler as People is not comparable
    // We can use simple comparator, but those have been tested above.
    // Thus choose to do compose for some level of interation.
    Comparator<People> cmp1 = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    Comparator<People> cmp = cmp1.thenComparing(cmp2);

    assertPairComparison(people[0], people[0], people[1], people[1],
                     Map.Entry.<People, People>comparingByKey(cmp),
                     Map.Entry.<People, People>comparingByValue(cmp));

}
 
Example 15
Project: freecol   File: ReportCompactColonyPanel.java   View Source Code Vote up 5 votes
private List<JButton> unitButtons(final Map<UnitType, Suggestion> suggestions,
                                  List<UnitType> have, Colony colony) {
    final String cac = colony.getId();
    List<JButton> result = new ArrayList<>();
    final Comparator<UnitType> buttonComparator
        = Comparator.comparing(ut -> suggestions.get(ut),
                               Suggestion.descendingAmountComparator);
    for (UnitType type : sort(suggestions.keySet(), buttonComparator)) {
        boolean present = have.contains(type);
        Suggestion suggestion = suggestions.get(type);
        String label = Integer.toString(suggestion.amount);
        ImageIcon icon
            = new ImageIcon(this.lib.getTinyUnitImage(type, false));
        StringTemplate tip = (suggestion.oldType == null)
            ? stpld("report.colony.wanting")
                .addName("%colony%", colony.getName())
                .addNamed("%unit%", type)
                .addStringTemplate("%location%",
                    suggestion.workLocation.getLabel())
                .addNamed("%goods%", suggestion.goodsType)
                .addAmount("%amount%", suggestion.amount)
            : stpld("report.colony.improving")
                .addName("%colony%", colony.getName())
                .addNamed("%oldUnit%", suggestion.oldType)
                .addNamed("%unit%", type)
                .addStringTemplate("%location%",
                    suggestion.workLocation.getLabel())
                .addNamed("%goods%", suggestion.goodsType)
                .addAmount("%amount%", suggestion.amount);
        JButton b = newButton(cac, label, icon,
                              (present) ? cGood : cPlain, tip);
        if (present) b.setFont(b.getFont().deriveFont(Font.BOLD));
        result.add(b);
    }
    return result;
}
 
Example 16
Project: SpaceGame   File: SpaceGame.java   View Source Code Vote up 4 votes
@Override
public void create() {
    //If we fail to create the assets path there is nothing we can do and we must exit
    try {
        Path assetsPath = Paths.get(SpaceGame.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        //If we are working in a development environment
        if (Files.isDirectory(assetsPath)) {
            assets = new File("").getAbsoluteFile().toPath();
        } else {
            //If we are working in a JAR file
            assets = FileSystems.newFileSystem(assetsPath, null).getPath("");
        }
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
        Gdx.app.exit();
    }
    
    //Set the static instance
    instance = this;
    
    //Do all important context pre-loading actions
    //This should do almost nothing
    context.preload();
    
    //Initialize very important instance variables
    delayedRunnables = new PriorityQueue<>(Comparator.comparing(Pair<Long, Runnable>::getFirst));
    eventBus = new EventBus();
    
    //All actual loading should occur in a seperate thread
    //This prevents loading from blocking the OpenGL context thread
    Thread loadingThread = new Thread(() -> {
        try {
            load();
            context.postload();
        } catch (Throwable throwable) {
            //If we failed to load exit the game
            throwable.printStackTrace();
            Gdx.app.exit();
        }
    }, "Loading Thread");
    //Loading thread should not stop the program from exiting
    loadingThread.setDaemon(true);
    loadingThread.start();
}
 
Example 17
Project: hashsdn-controller   File: RuntimeBeanEntry.java   View Source Code Vote up 4 votes
private static Collection<DataSchemaNode> sortAttributes(final Collection<DataSchemaNode> childNodes) {
    final TreeSet<DataSchemaNode> dataSchemaNodes =
            new TreeSet<>(Comparator.comparing(o -> o.getQName().getLocalName()));
    dataSchemaNodes.addAll(childNodes);
    return dataSchemaNodes;
}
 
Example 18
Project: sporticus   File: Functions.java   View Source Code Vote up 2 votes
/**
 * Sorts collections of items ignoring the order of the items i.e. {a, b} == {b, a}
 *
 * @param singleItemComparator A comparator for a the items in the collections
 * @param <T>                  The type of time
 * @return A comparator for collections of items
 */
public static <T> Comparator<Collection<T>> getCollectionComparator(Comparator<T> singleItemComparator) {
	return Comparator.comparing(a -> a.stream().sorted(singleItemComparator).collect(Collectors.toList()), getListComparator(singleItemComparator));
}
 
Example 19
Project: guava-mock   File: Comparators.java   View Source Code Vote up 2 votes
/**
 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as less
 * than all other values, and orders the rest using {@code valueComparator} on the contained
 * value.
 *
 * @since 22.0
 */
@Beta
public static <T> Comparator<Optional<T>> emptiesFirst(Comparator<T> valueComparator) {
  checkNotNull(valueComparator);
  return Comparator.comparing(o -> o.orElse(null), Comparator.nullsFirst(valueComparator));
}
 
Example 20
Project: guava-mock   File: Comparators.java   View Source Code Vote up 2 votes
/**
 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as greater
 * than all other values, and orders the rest using {@code valueComparator} on the contained
 * value.
 *
 * @since 22.0
 */
@Beta
public static <T> Comparator<Optional<T>> emptiesLast(Comparator<T> valueComparator) {
  checkNotNull(valueComparator);
  return Comparator.comparing(o -> o.orElse(null), Comparator.nullsLast(valueComparator));
}