Java8: Streams

Nuwan Zen
2 min readMar 16, 2021

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.

Photo by Good Free Photos on Unsplash
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.

validNames.forEach(System.out::println);

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.

squaresList.forEach(System.out::println);

Let’s limit the steam to three and print everything.

squaresList.stream().limit(3).forEach(System.out::println);

Sort and print

squaresList.stream().sorted().forEach(System.out::println);

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.

System.out.println("Count: "+squaresList.parallelStream().count());

Read my other blogs:

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!