Tabnine Logo
Comparator
Code IndexAdd Tabnine to your IDE (free)

How to use
Comparator
in
java.util

Best Java code snippets using java.util.Comparator (Showing top 20 results out of 32,247)

Refine searchRefine arrow

  • Stream
  • Collectors
  • Optional
  • Benchmark
  • IntStream
origin: square/okhttp

public static int indexOf(Comparator<String> comparator, String[] array, String value) {
 for (int i = 0, size = array.length; i < size; i++) {
  if (comparator.compare(array[i], value) == 0) return i;
 }
 return -1;
}
origin: hs-web/hsweb-framework

private static Map<String, ClassProperty> createProperty(Class type) {
  List<String> fieldNames = Arrays.stream(type.getDeclaredFields())
      .map(Field::getName).collect(Collectors.toList());
  return Stream.of(propertyUtils.getPropertyDescriptors(type))
      .filter(property -> !property.getName().equals("class") && property.getReadMethod() != null && property.getWriteMethod() != null)
      .map(BeanClassProperty::new)
      //让字段有序
      .sorted(Comparator.comparing(property -> fieldNames.indexOf(property.name)))
      .collect(Collectors.toMap(ClassProperty::getName, Function.identity(), (k, k2) -> k, LinkedHashMap::new));
}
origin: goldmansachs/gs-collections

@Benchmark
public void serial_lazy_jdk()
{
  Map<Alphagram, List<String>> groupBy = this.jdkWords.stream().collect(Collectors.groupingBy(Alphagram::new));
  groupBy.entrySet()
      .stream()
      .map(Map.Entry::getValue)
      .filter(list -> list.size() >= SIZE_THRESHOLD)
      .sorted(Comparator.<List<String>>comparingInt(List::size).reversed())
      .map(list -> list.size() + ": " + list)
      .forEach(e -> Assert.assertFalse(e.isEmpty()));
}
origin: dropwizard/dropwizard

  @Override
  public int compare(EndpointLogLine endpointA, EndpointLogLine endpointB) {
    return Comparator.<EndpointLogLine, String>comparing(endpoint -> endpoint.basePath)
        .thenComparing(endpoint -> endpoint.httpMethod, Comparator.nullsLast(Comparator.naturalOrder()))
        .compare(endpointA, endpointB);
  }
}
origin: apache/incubator-druid

@Override
public Comparator<String> getComparator()
{
 return Comparator.nullsFirst(Comparator.naturalOrder());
}
origin: google/guava

/**
 * 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<? super T> valueComparator) {
 checkNotNull(valueComparator);
 return Comparator.comparing(o -> o.orElse(null), Comparator.nullsFirst(valueComparator));
}
origin: apache/flink

  default List<MessageHeaders> getSpecs() {
    Comparator<String> comparator = new RestServerEndpoint.RestHandlerUrlComparator.CaseInsensitiveOrderComparator();
    return initializeHandlers(CompletableFuture.completedFuture(null)).stream()
      .map(tuple -> tuple.f0)
      .filter(spec -> spec instanceof MessageHeaders)
      .map(spec -> (MessageHeaders) spec)
      .sorted((spec1, spec2) -> comparator.compare(spec1.getTargetRestEndpointURL(), spec2.getTargetRestEndpointURL()))
      .collect(Collectors.toList());
  }
}
origin: biezhi/learn-java8

.filter(transaction -> transaction.year == 2011)
.sorted(Comparator.comparing(Transaction::getValue))
.collect(Collectors.toList());
.map(Trader::getCity)
.distinct()
.collect(Collectors.toList());
.map(Transaction::getTrader)
.filter(trader -> trader.getCity().equals("Cambridge"))
.sorted(Comparator.comparing(Trader::getName))
.collect(Collectors.toList());
.map(Transaction::getTrader)
.map(Trader::getName)
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
.mapToInt(Transaction::getValue)
.max();
origin: SonarSource/sonarqube

private void writeScannerProps(BufferedWriter fileWriter, Map<String, String> props) throws IOException {
 for (Map.Entry<String, String> prop : props.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).collect(toList())) {
  if (isSystemProp(prop.getKey()) || isEnvVariable(prop.getKey()) || !isSqProp(prop.getKey())) {
   continue;
  }
  dumpPropIfNotSensitive(fileWriter, prop.getKey(), prop.getValue());
 }
}
origin: Alluxio/alluxio

private List<URIStatus> sortByFieldAndOrder(
    List<URIStatus> statuses, String sortField, boolean reverse) throws IOException {
 Optional<Comparator<URIStatus>> sortToUse = Optional.ofNullable(
     SORT_FIELD_COMPARATORS.get(sortField));
 if (!sortToUse.isPresent()) {
  throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_SORT_FIELD
    .getMessage(sortField));
 }
 Comparator<URIStatus> sortBy = sortToUse.get();
 if (reverse) {
  sortBy = sortBy.reversed();
 }
 return statuses.stream().sorted(sortBy).collect(Collectors.toList());
}
origin: SonarSource/sonarqube

protected void assertResultOrder(String query, String... resultsInOrder) {
 ComponentDto project = indexProject("key-1", "Quality Product");
 List<ComponentDto> files = Arrays.stream(resultsInOrder)
  .map(r -> ComponentTesting.newFileDto(project).setName(r))
  .peek(f -> f.setUuid(f.uuid() + "_" + f.name().replaceAll("[^a-zA-Z0-9]", "")))
  .collect(Collectors.toList());
 // index them, but not in the expected order
 files.stream()
  .sorted(Comparator.comparing(ComponentDto::uuid).reversed())
  .forEach(this::index);
 assertExactResults(query, files.toArray(new ComponentDto[0]));
}
origin: SonarSource/sonarqube

@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
 Predicate<Map.Entry<TextBlock, Integer>> containsLine = new TextBlockContainsLine(lineBuilder.getLine());
 // list is sorted to cope with the non-guaranteed order of Map entries which would trigger false detection of changes
 // in {@link DbFileSources.Line#getDuplicationList()}
 duplicatedTextBlockIndexByTextBlock.entrySet().stream()
  .filter(containsLine)
  .map(Map.Entry::getValue)
  .sorted(Comparator.naturalOrder())
  .forEach(lineBuilder::addDuplication);
 return Optional.empty();
}
origin: prestodb/presto

public Expression toPredicate(TupleDomain<Symbol> tupleDomain)
{
  if (tupleDomain.isNone()) {
    return FALSE_LITERAL;
  }
  Map<Symbol, Domain> domains = tupleDomain.getDomains().get();
  return domains.entrySet().stream()
      .sorted(comparing(entry -> entry.getKey().getName()))
      .map(entry -> toPredicate(entry.getValue(), entry.getKey().toSymbolReference()))
      .collect(collectingAndThen(toImmutableList(), ExpressionUtils::combineConjuncts));
}
origin: spring-projects/spring-framework

@Test
public void testStringArrayToResourceArray() {
  conversionService.addConverter(new MyStringArrayToResourceArrayConverter());
  Resource[] converted = conversionService.convert(new String[] { "x1", "z3" }, Resource[].class);
  List<String> descriptions = Arrays.stream(converted).map(Resource::getDescription).sorted(naturalOrder()).collect(toList());
  assertEquals(Arrays.asList("1", "3"), descriptions);
}
origin: zstackio/zstack

logger.debug(String.format("before PrimaryStoragePrioritySortFlow adjustCandidates: %s", candidates.stream().map(HostInventory::getName).collect(Collectors.toList())));
String psPriorityCondition = String.join(" ", priMap.stream()
    .map(it -> String.format("when '%s' then %d", it.PS, it.priority))
    .collect(Collectors.toList()));
logger.debug(String.format("ps priority condition : %s", psPriorityCondition));
    " and pr.uuid=ref.primaryStorageUuid " +
    " group by h.uuid", Tuple.class)
    .param("huuids", candidates.stream().map(HostInventory::getUuid).collect(Collectors.toList()))
    .param("defaultPriority", defaultPriroty)
    .list();
    .peek(it -> hostPriority.put(it.get(1, String.class), it.get(0, Integer.class)))
    .mapToInt(it -> it.get(0, Integer.class))
    .min().orElse(defaultPriroty);
    .sorted(Comparator.comparingInt(it -> hostPriority.get(it.getUuid())))
    .collect(Collectors.toList());
candidates.clear();
origin: apache/flink

private static void printJobStatusMessages(List<JobStatusMessage> jobs) {
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
  Comparator<JobStatusMessage> startTimeComparator = (o1, o2) -> (int) (o1.getStartTime() - o2.getStartTime());
  Comparator<Map.Entry<JobStatus, List<JobStatusMessage>>> statusComparator =
    (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getKey().toString(), o2.getKey().toString());
  Map<JobStatus, List<JobStatusMessage>> jobsByState = jobs.stream().collect(Collectors.groupingBy(JobStatusMessage::getJobState));
  jobsByState.entrySet().stream()
    .sorted(statusComparator)
    .map(Map.Entry::getValue).flatMap(List::stream).sorted(startTimeComparator)
    .forEachOrdered(job ->
      System.out.println(dateFormat.format(new Date(job.getStartTime()))
        + " : " + job.getJobId() + " : " + job.getJobName()
        + " (" + job.getJobState() + ")"));
}
origin: neo4j/neo4j

  @Override
  public String toString()
  {
    return params.entrySet().stream()
        .sorted( Comparator.comparing( Map.Entry::getKey ) )
        .map( entry -> entry.getKey() + "=" + obsfucateIfSecret( entry ) )
        .collect( Collectors.joining( ", ") );
  }
}
origin: RankSys/RankSys

/**
 * Constructor.
 *
 * @param data preference data
 */
public PopularityRecommender(FastPreferenceData<U, I> data) {
  super(data, data);
  popList = data.getIidxWithPreferences()
      .mapToObj(iidx -> tuple(iidx, (double) data.numUsers(iidx)))
      .sorted(comparingDouble(Tuple2id::v2).reversed())
      .collect(toList());
}
origin: neo4j/neo4j

public String usage()
{
  StringBuilder sb = new StringBuilder();
  if ( !namedArgs.isEmpty() )
  {
    sb.append( namedArgs.values().stream().map( NamedArgument::usage ).collect( Collectors.joining( " " ) ) );
  }
  if ( !positionalArgs.isEmpty() )
  {
    sb.append( " " );
    positionalArgs.sort( Comparator.comparingInt( PositionalArgument::position ) );
    sb.append( positionalArgs.stream().map( PositionalArgument::usage ).collect( Collectors.joining( " " ) ) );
  }
  return sb.toString().trim();
}
origin: SonarSource/sonarqube

private String printStatusesAndTypes(@Nullable Set<NodeHealth> nodeHealths) {
 if (nodeHealths == null) {
  return "<null>";
 }
 return nodeHealths.stream()
  // sort by type then status for debugging convenience
  .sorted(Comparator.<NodeHealth>comparingInt(s1 -> s1.getDetails().getType().ordinal())
   .thenComparingInt(s -> s.getStatus().ordinal()))
  .map(s -> ImmutableList.of(s.getDetails().getType().name(), s.getStatus().name()))
  .map(String::valueOf)
  .collect(Collectors.joining(","));
}
java.utilComparator

Javadoc

A Comparator is used to compare two objects to determine their ordering with respect to each other. On a given Collection, a Comparator can be used to obtain a sorted Collection which is totally ordered. For a Comparatorto be consistent with equals, its {code #compare(Object, Object)} method has to return zero for each pair of elements (a,b) where a.equals(b) holds true. It is recommended that a Comparator implements java.io.Serializable.

Most used methods

  • compare
  • comparing
  • comparingInt
  • naturalOrder
  • reversed
  • thenComparing
  • comparingLong
  • reverseOrder
  • equals
    Compares this Comparator with the specified Object and indicates whether they are equal. In order to
  • comparingDouble
  • nullsFirst
  • nullsLast
  • nullsFirst,
  • nullsLast,
  • thenComparingInt,
  • thenComparingLong,
  • thenComparingDouble,
  • <init>

Popular in Java

  • Running tasks concurrently on multiple threads
  • getContentResolver (Context)
  • scheduleAtFixedRate (ScheduledExecutorService)
  • runOnUiThread (Activity)
  • Point (java.awt)
    A point representing a location in (x,y) coordinate space, specified in integer precision.
  • PrintStream (java.io)
    Fake signature of an existing Java class.
  • Deque (java.util)
    A linear collection that supports element insertion and removal at both ends. The name deque is shor
  • Hashtable (java.util)
    A plug-in replacement for JDK1.5 java.util.Hashtable. This version is based on org.cliffc.high_scale
  • JButton (javax.swing)
  • JLabel (javax.swing)
  • Top plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now