Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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 156 views
1 answer 83 views
83 views asked Mar 11, 2023 by avibootz
2 answers 141 views
141 views asked Sep 28, 2019 by avibootz
1 answer 206 views
2 answers 114 views
114 views asked Oct 5, 2023 by avibootz
...