本文整理了Java中java.util.Comparator
类的一些代码示例,展示了Comparator
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Comparator
类的具体详情如下:
包路径:java.util.Comparator
类名称:Comparator
[英]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.
[中]比较器用于比较两个对象,以确定它们之间的顺序。在给定集合上,可以使用比较器获得完全有序的已排序集合。为了使comparator与equals一致,它的{code#compare(Object,Object)}方法必须为a.equals(b)为真的每对元素(a,b)返回零。建议比较器实现java。木卫一。可序列化。
代码示例来源: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(","));
}
内容来源于网络,如有侵权,请联系作者删除!