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

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

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

Collectors.reducing介绍

暂无

代码示例

代码示例来源:origin: eclipse/eclipse-collections

/**
 * Returns a BigDecimal sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(Function<? super T, BigDecimal> function)
{
  return Collectors.reducing(BigDecimal.ZERO, function, BigDecimal::add);
}

代码示例来源:origin: eclipse/eclipse-collections

/**
 * Returns a BigInteger sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigInteger> summingBigInteger(Function<? super T, BigInteger> function)
{
  return Collectors.reducing(BigInteger.ZERO, function, BigInteger::add);
}

代码示例来源:origin: eclipse/eclipse-collections

/**
 * Returns a BigInteger sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigInteger> summingBigInteger(Function<? super T, BigInteger> function)
{
  return Collectors.reducing(BigInteger.ZERO, function, BigInteger::add);
}

代码示例来源:origin: eclipse/eclipse-collections

/**
 * Returns a BigDecimal sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(Function<? super T, BigDecimal> function)
{
  return Collectors.reducing(BigDecimal.ZERO, function, BigDecimal::add);
}

代码示例来源:origin: codecentric/spring-boot-admin

private void compact(List<InstanceEvent> events) {
  BinaryOperator<InstanceEvent> latestEvent = (e1, e2) -> e1.getVersion() > e2.getVersion() ? e1 : e2;
  Map<Class<?>, Optional<InstanceEvent>> latestPerType = events.stream()
                                 .collect(groupingBy(InstanceEvent::getClass,
                                   reducing(latestEvent)));
  events.removeIf((e) -> !Objects.equals(e, latestPerType.get(e.getClass()).orElse(null)));
}

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

public static Optional<Amount> cheapestFare(Map<String, Fare> fares, Trip trip) {
  return ticketsBruteForce(fares, trip)
      .flatMap(tickets -> tickets.stream()
          .map(ticket -> {
            Fare fare = fares.get(ticket.getFare().fare_id);
            final BigDecimal priceOfOneTicket = BigDecimal.valueOf(fare.fare_attribute.price);
            return new Amount(priceOfOneTicket, fare.fare_attribute.currency_type);
          })
          .collect(Collectors.groupingBy(Amount::getCurrencyType, Collectors.mapping(Amount::getAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))))
          .entrySet()
          .stream()
          .findFirst() // TODO: Tickets in different currencies for one trip
          .map(e -> new Amount(e.getValue(), e.getKey())));
}

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public static String formatArtistsReducing(List<Artist> artists) {
    // BEGIN reducing
String result =
    artists.stream()
        .map(Artist::getName)
        .collect(Collectors.reducing(
          new StringCombiner(", ", "[", "]"),
          name -> new StringCombiner(", ", "[", "]").add(name),
          StringCombiner::merge))
        .toString();
    // END reducing
    return result;
  }

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public static final Collector<AlbumSale, ?, AlbumSalesReport>
    reportingAlbumSales() {
  return Collectors.reducing(new AlbumSalesReport(), album -> new AlbumSalesReport(album), (left, right) -> left.merge(right));
}

代码示例来源:origin: biezhi/learn-java8

public static void main(String[] args) {
    List<Project> projects = Project.buildData();
    Double collect = projects.stream()
        .collect(averagingInt(Project::getStars));
    System.out.println(collect);

    System.out.println(Stream.of("Hello", "Java8")
        .collect(joining(",")));

    Integer collect1 = projects.stream()
        .collect(reducing(0, Project::getStars, (x, y) -> x + y));
    System.out.println(collect1);

    Optional<Integer> collect2 = projects.stream()
        .map(Project::getStars)
        .collect(reducing((x, y) -> x + y));
    System.out.println(collect2);
  }
}

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

@Procedure("apoc.search.nodeReduced")
@Description("Do a parallel search over multiple indexes returning a reduced representation of the nodes found: node id, labels and the searched properties. apoc.search.nodeReduced( map of label and properties which will be searched upon, operator: EXACT | CONTAINS | STARTS WITH | ENDS WITH, searchValue ). Multiple search results for the same node are merged into one record.")
public Stream<NodeReducedResult> multiSearch(@Name("LabelPropertyMap") final Object labelProperties, @Name("operator") final String operator, @Name("value") final String value) throws Exception {
  return createWorkersFromValidInput(labelProperties, operator, value)
        .flatMap(QueryWorker::queryForData)
        .collect(groupingBy(res -> res.id,Collectors.reducing(this::merge)))
        .values().stream().filter(Optional::isPresent).map(Optional::get);
}

代码示例来源:origin: org.jooq/jool

/**
 * Get a {@link Collector} that calculates the <code>LAST</code> function.
 * <p>
 * Note that unlike in (Oracle) SQL, where the <code>FIRST</code> function 
 * is an ordered set aggregate function that produces a set of results, this
 * collector just produces the first value in the order of stream traversal.
 * For matching behaviour to Oracle's [ aggregate function ] KEEP 
 * (DENSE_RANK LAST ORDER BY ... ), use {@link #minAll(Comparator)} instead.
 */
public static <T> Collector<T, ?, Optional<T>> last() {
  return Collectors.reducing((v1, v2) -> v2);
}

代码示例来源:origin: org.jooq/jool

/**
 * Get a {@link Collector} that calculates the <code>FIRST</code> function.
 * <p>
 * Note that unlike in (Oracle) SQL, where the <code>FIRST</code> function 
 * is an ordered set aggregate function that produces a set of results, this
 * collector just produces the first value in the order of stream traversal.
 * For matching behaviour to Oracle's [ aggregate function ] KEEP 
 * (DENSE_RANK FIRST ORDER BY ... ), use {@link #maxAll(Comparator)} instead.
 */
public static <T> Collector<T, ?, Optional<T>> first() {
  return Collectors.reducing((v1, v2) -> v1);
}

代码示例来源:origin: one.util/streamex

/**
 * Returns a {@code Collector} which collects only the last stream element
 * if any.
 * 
 * @param <T> the type of the input elements
 * @return a collector which returns an {@link Optional} which describes the
 *         last element of the stream. For empty stream an empty
 *         {@code Optional} is returned.
 */
public static <T> Collector<T, ?, Optional<T>> last() {
  return Collectors.reducing((u, v) -> v);
}

代码示例来源:origin: org.eclipse.collections/eclipse-collections

/**
 * Returns a BigInteger sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigInteger> summingBigInteger(Function<? super T, BigInteger> function)
{
  return Collectors.reducing(BigInteger.ZERO, function, BigInteger::add);
}

代码示例来源:origin: org.eclipse.collections/eclipse-collections

/**
 * Returns a BigDecimal sum applying the specified function to each element of the stream or collection.
 *
 * @since 8.1
 */
public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(Function<? super T, BigDecimal> function)
{
  return Collectors.reducing(BigDecimal.ZERO, function, BigDecimal::add);
}

代码示例来源:origin: kennycason/kumo

private Map<String, Integer> buildWordFrequencies(final List<String> texts, final WordTokenizer tokenizer) {
  return texts.stream()
        .map(tokenizer::tokenize)
        .flatMap(List::stream)
        .map(this::normalize)
        .filter(buildFilter())
        .collect(Collectors.groupingBy(e -> e, reducing(0, e -> 1, Integer::sum)));
}

代码示例来源:origin: org.controlsfx/controlsfx

/**
 * Combines the given validators into a single Validator instance. 
 * @param validators the validators to combine
 * @return a Validator instance
 */
@SafeVarargs
static <T> Validator<T> combine(Validator<T>... validators) {
  return (control, value) -> Stream.of(validators)
    .map(validator -> validator.apply(control, value))
    .collect(Collectors.reducing(new ValidationResult(), ValidationResult::combine));
}

代码示例来源:origin: FundRequest/platform

public List<FundsByFunderDto> aggregate(final List<T> funds) {
  return funds.stream()
        .collect(Collectors.groupingBy(fund -> getFunderAddress(fund) + getFundedBy(fund),
                        Collectors.mapping(mapToFundsByFunderDto(), Collectors.reducing(sumFunds()))))
        .values()
        .stream()
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());
}

代码示例来源:origin: sdaschner/jaxrs-analyzer

private void consolidateMultipleMethodsForSamePath(String path, Set<ResourceMethod> resourceMethods) {
  resourceMethods.stream()
      .collect(Collectors.groupingBy(m -> m.getMethod().toString().toLowerCase(),
          Collectors.reducing(new ResourceMethod(), ResourceMethod::combine))
      ).forEach((k, v) -> addMethod(path, v));
}

代码示例来源:origin: OpenGamma/Strata

public void toMapGroupingWithCollector() {
 Map<String, Integer> map = ImmutableMap.of("a", 1, "aa", 2, "b", 10, "bb", 20, "c", 1);
 Map<String, Integer> expected = ImmutableMap.of("a", 3, "b", 30, "c", 1);
 Map<String, Integer> result = MapStream.of(map).mapKeys(s -> s.substring(0, 1))
   .toMapGrouping(reducing(0, Integer::sum));
 assertThat(result).isEqualTo(expected);
}

相关文章