Java 8 introduced a new feature to manage objects in sequential order. This can be considered as a series of objects are coming in a pipeline and we doing some processing per object.
List<String> names = Arrays.asList("nuwan","","chamara","sena");
List<String> validNames = names.stream().filter(s ->!s.isEmpty()).collect(Collectors.toList());
This example will create a list and then convert it to stream in the second line. then filter is used to check whether the item is empty. Then finally collect method will convert the stream in to a list.
System.out.println( validNames.stream().collect(Collectors.joining(", ")));
In this code we convert the stream in to a string instead of list created before.
We can print this list using forEach method comes in collections framework. This System.out::println can be written as num -> System.out.println(num) known as method reference.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
List<Integer> squaresList =numbers.stream()
.map(i -> i*i).distinct().collect(Collectors.toList());
Now let’s get a list of integers and square it and then find unique numbers and convert in to a list.
This will print the above processed list.
Let’s limit the steam to three and print everything.
Sort and print
Let’s use the summary statistics class and print the output
IntSummaryStatistics statistics = squaresList.stream().mapToInt(i -> i).summaryStatistics();
System.out.println("Stats: "+statistics.getMax()+" "+ statistics.getSum()+" "+ statistics.getAverage());
Let’s try to use parallel stream feature to count the items in the array using multi-core hardware resources.
Read my other blogs: