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

How to use reduce in java

WBOY
Release: 2023-05-01 15:43:16
forward
1908 people have browsed it

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);
Copy after login

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"
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template