java.util.stream.Collectors.collectingAndThen()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.5k)|赞(0)|评价(0)|浏览(235)

本文整理了Java中java.util.stream.Collectors.collectingAndThen()方法的一些代码示例,展示了Collectors.collectingAndThen()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collectors.collectingAndThen()方法的具体详情如下:
包路径:java.util.stream.Collectors
类名称:Collectors
方法名:collectingAndThen

Collectors.collectingAndThen介绍

暂无

代码示例

代码示例来源:origin: google/guava

/**
 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
 * and values are the result of applying the provided mapping functions to the input elements.
 *
 * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the
 * values are merged using the specified merging function. Entries will appear in the encounter
 * order of the first occurrence of the key.
 *
 * @since 21.0
 */
@Beta
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
  Function<? super T, ? extends K> keyFunction,
  Function<? super T, ? extends V> valueFunction,
  BinaryOperator<V> mergeFunction) {
 checkNotNull(keyFunction);
 checkNotNull(valueFunction);
 checkNotNull(mergeFunction);
 return Collectors.collectingAndThen(
   Collectors.toMap(keyFunction, valueFunction, mergeFunction, LinkedHashMap::new),
   ImmutableMap::copyOf);
}

代码示例来源:origin: apache/kafka

public static <T> List<T> concatLists(List<T> left, List<T> right, Function<List<T>, List<T>> finisher) {
  return Stream.concat(left.stream(), right.stream())
      .collect(Collectors.collectingAndThen(Collectors.toList(), finisher));
}

代码示例来源:origin: google/guava

/**
 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose
 * keys and values are the result of applying the provided mapping functions to the input
 * elements.
 *
 * <p>If the mapped keys contain duplicates (according to the comparator), the the values are
 * merged using the specified merging function. Entries will appear in the encounter order of the
 * first occurrence of the key.
 *
 * @since 21.0
 */
@Beta
public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
  Comparator<? super K> comparator,
  Function<? super T, ? extends K> keyFunction,
  Function<? super T, ? extends V> valueFunction,
  BinaryOperator<V> mergeFunction) {
 checkNotNull(comparator);
 checkNotNull(keyFunction);
 checkNotNull(valueFunction);
 checkNotNull(mergeFunction);
 return Collectors.collectingAndThen(
   Collectors.toMap(
     keyFunction, valueFunction, mergeFunction, () -> new TreeMap<K, V>(comparator)),
   ImmutableSortedMap::copyOfSorted);
}

代码示例来源:origin: speedment/speedment

public static <T> Collector<T, ?, List<T>> toReversedList() {
  return Collectors.collectingAndThen(Collectors.toList(), l -> {
    Collections.<T>reverse(l);
    return l;
  });
}

代码示例来源:origin: knowm/XChange

public static <T> Collector<T, ?, T> singletonCollector() {
  return Collectors.collectingAndThen(
    Collectors.toList(),
    list -> {
     if (list.size() > 1) {
      throw new IllegalStateException("List contains more than one element: " + list);
     }
     return list.size() > 0 ? list.get(0) : null;
    });
 }
}

代码示例来源:origin: SonarSource/sonarqube

/**
 * For stream of one expected element, return the element
 *
 * @throws IllegalArgumentException if stream has no element or more than 1 element
 */
public static <T> Collector<T, ?, T> toOneElement() {
 return java.util.stream.Collectors.collectingAndThen(
  java.util.stream.Collectors.toList(),
  list -> {
   if (list.size() != 1) {
    throw new IllegalStateException("Stream should have only one element");
   }
   return list.get(0);
  });
}

代码示例来源:origin: apache/incubator-druid

private List<String> prepareDimensionsOrMetrics(@Nullable List<String> list, Interner<List<String>> interner)
{
 if (list == null) {
  return ImmutableList.of();
 } else {
  List<String> result = list
    .stream()
    .filter(s -> !Strings.isNullOrEmpty(s))
    // dimensions & metrics are stored as canonical string values to decrease memory required for storing
    // large numbers of segments.
    .map(STRING_INTERNER::intern)
    // TODO replace with ImmutableList.toImmutableList() when updated to Guava 21+
    .collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
  return interner.intern(result);
 }
}

代码示例来源:origin: speedment/speedment

/**
 * Creates and returns a new unmodifiable list of immutable Stage object
 *
 * @return a new unmodifiable list of immutable Stage object
 */
List<Stage<?>> stages() {
  resolveStages();
  return stageBeans.stream()
    .map(StageBean::asStage)
    .collect(collectingAndThen(toList(), Collections::unmodifiableList));
}

代码示例来源:origin: graphhopper/graphhopper

static List<SanitizedFareRule> sanitizeFareRules(List<FareRule> gtfsFareRules) {
  // Make proper fare rule objects from the CSV-like FareRule
  ArrayList<SanitizedFareRule> result = new ArrayList<>();
  result.addAll(gtfsFareRules.stream().filter(rule -> rule.route_id != null).map(rule -> new RouteRule(rule.route_id)).collect(toList()));
  result.addAll(gtfsFareRules.stream().filter(rule -> rule.origin_id != null && rule.destination_id != null).map(rule -> new OriginDestinationRule(rule.origin_id, rule.destination_id)).collect(toList()));
  result.add(gtfsFareRules.stream().filter(rule -> rule.contains_id != null).map(rule -> rule.contains_id).collect(Collectors.collectingAndThen(toList(), ZoneRule::new)));
  return result;
}

代码示例来源:origin: pmd/pmd

AstPackageExplorer(Language language) {
  availableNodeNames =
    getClassesInPackage("net.sourceforge.pmd.lang." + language.getTerseName() + ".ast")
      .filter(clazz -> clazz.getSimpleName().startsWith("AST"))
      .filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
      .map(m -> m.getSimpleName().substring("AST".length()))
      .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}

代码示例来源:origin: org.assertj/assertj-core

private <T> List<T> simplePropertyValues(String propertyName, Class<T> clazz, Iterable<?> target) {
 return stream(target).map(e -> e == null ? null : propertyValue(propertyName, clazz, e))
            .collect(collectingAndThen(toList(), Collections::unmodifiableList));
}

代码示例来源:origin: hs-web/hsweb-framework

@Override
  public TaskEventListener getTaskListener(String eventType) {
    if (CollectionUtils.isEmpty(configEntity.getListeners())) {
      return null;
    }
    return configEntity
        .getListeners()
        .stream()
        .filter(config -> eventType.equals(config.getEventType()))
        .map(ProcessConfigurationServiceImpl.this::<TaskEvent>createTaskEventListener)
        .collect(Collectors.collectingAndThen(Collectors.toList(),
            list -> event -> list.forEach(listener -> listener.accept(event))));
  }
};

代码示例来源: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: org.assertj/assertj-core

private <T> List<T> simpleFieldValues(String fieldName, Class<T> clazz, Iterable<?> target) {
 return stream(target).map(e -> e == null ? null : fieldValue(fieldName, clazz, e))
            .collect(collectingAndThen(toList(), Collections::unmodifiableList));
}

代码示例来源:origin: hs-web/hsweb-framework

@Override
  public ProcessEventListener getProcessListener(String eventType) {
    if (CollectionUtils.isEmpty(entity.getListeners())) {
      return null;
    }
    return entity
        .getListeners()
        .stream()
        .filter(config -> eventType.equals(config.getEventType()))
        .map(ProcessConfigurationServiceImpl.this::<ProcessEvent>createTaskEventListener)
        .collect(Collectors.collectingAndThen(Collectors.toList(),
            list -> event -> list.forEach(listener -> listener.accept(event))));
  }
};

代码示例来源:origin: google/guava

checkNotNull(keyFunction);
checkNotNull(valuesFunction);
return Collectors.collectingAndThen(
  Multimaps.flatteningToMultimap(
    input -> checkNotNull(keyFunction.apply(input)),

代码示例来源:origin: google/guava

checkNotNull(keyFunction);
checkNotNull(valuesFunction);
return Collectors.collectingAndThen(
  Multimaps.flatteningToMultimap(
    input -> checkNotNull(keyFunction.apply(input)),

代码示例来源:origin: google/error-prone

private static Collector<JCVariableDecl, ?, ImmutableMultimap<Integer, JCVariableDecl>>
  collectByEditDistanceTo(String baseName) {
 return Collectors.collectingAndThen(
   Multimaps.toMultimap(
     (JCVariableDecl varDecl) ->
       LevenshteinEditDistance.getEditDistance(baseName, varDecl.name.toString()),
     varDecl -> varDecl,
     LinkedHashMultimap::create),
   ImmutableMultimap::copyOf);
}

代码示例来源:origin: graphql-java/graphql-java

public CompletableFuture<List<Project>> getProjectsForCompanies(List<UUID> companyIds) {
  return CompletableFuture.supplyAsync(() -> projects.values().stream()
      .filter(project -> companyIds.contains(project.getCompanyId()))
      .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
}

代码示例来源:origin: prestodb/presto

/**
 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
 * and values are the result of applying the provided mapping functions to the input elements.
 *
 * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the
 * values are merged using the specified merging function. Entries will appear in the encounter
 * order of the first occurrence of the key.
 *
 * @since 21.0
 */
@Beta
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
  Function<? super T, ? extends K> keyFunction,
  Function<? super T, ? extends V> valueFunction,
  BinaryOperator<V> mergeFunction) {
 checkNotNull(keyFunction);
 checkNotNull(valueFunction);
 checkNotNull(mergeFunction);
 return Collectors.collectingAndThen(
   Collectors.toMap(keyFunction, valueFunction, mergeFunction, LinkedHashMap::new),
   ImmutableMap::copyOf);
}

相关文章