Home >Java >javaTutorial >How to use reduce in java

How to use reduce in java

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-05-01 15:43:161971browse

1. Description

There are three overloaded methods to generate a value from a stream.

Optional<T> reduce(BinaryOperator<T> accumulator);
 
T reduce(T identity, BinaryOperator<T> accumulator);
 
 <U> U reduce(U identity,
                 BiFunction<U, ? super T, U> accumulator,
                 BinaryOperator<U> combiner);

2. Example

reduce means to reduce. Through the participating Function, we can classify the list into a value. Its return type is Optional.

Optional<String> reduced =
    stringCollection
        .stream()
        .sorted()
        .reduce((s1, s2) -> s1 + "#" + s2);
 
reduced.ifPresent(System.out::println);
// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"

What is Java

Java is an object-oriented programming language that can write desktop applications, Web applications, distributed systems and embedded system applications.

The above is the detailed content of How to use reduce in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete