How to use stream reduce in Java

3 Answers

0 votes
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;

public class MyClass
{
    public static void main(String[] args)
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
    
        int result = list
                .stream()
                .reduce(0, (subtotal, element) -> subtotal + element); 

        System.out.println(result);
    }
}




/*
run:

28

*/

 



answered Mar 14, 2023 by avibootz
0 votes
import java.util.stream.Stream;
import java.util.Optional;
import java.util.Arrays;
import java.util.List;

public class MyClass
{
    public static void main(String[] args)
    {
        List<String> list = Arrays.asList("java", "c", "python", "c++", "rust");
        
        Optional<String> longestString = list.stream()
                                        .reduce((word1, word2)
                                        -> word1.length() > word2.length() ? word1 : word2);
                                        
        longestString.ifPresent(System.out::println);
    }
}




/*
run:

python

*/

 



answered Mar 14, 2023 by avibootz
0 votes
import java.util.stream.Stream;
import java.util.Optional;
import java.util.Arrays;

public class MyClass
{
    public static void main(String[] args)
    {
        String[] array = {"java", "c", "python", "cpp", "rust"};
        
        Optional<String> StringConcat = Arrays.stream(array)
                                        .reduce((str1, str2) -> str1 + "::" + str2);
                                        
        StringConcat.ifPresent(System.out::println);
    }
}




/*
run:

java::c::python::cpp::rust

*/

 



answered Mar 14, 2023 by avibootz

Related questions

1 answer 167 views
1 answer 92 views
92 views asked Mar 11, 2023 by avibootz
2 answers 162 views
162 views asked Sep 28, 2019 by avibootz
1 answer 223 views
2 answers 123 views
123 views asked Oct 5, 2023 by avibootz
...