Java 8 streams examples that you should use


If you do programming as part of your day to day life, you will encounter loops multiple times a day. Java 8 stream APIs are pretty handy for various activities. Let me through in some useful examples that you can use in your day to day life.

For downloading complete example, you can visit the following github repository link.

Let us first just define a list and add some elements in it.

List<String> list = new ArrayList<>();

Now print all elements of the list. -> System.out.print(val+","));

Print all elements starting with A. -> val.startsWith("A")).forEach(val -> System.out.print(val+","));

Find all names matching a given condition.

System.out.println(> val.contains("m")));

Find any names matching a given condition.

System.out.println( -> val.startsWith("M")));

Collect the elements to a new list after performing a specific filter. -> val.startsWith("P")).collect(Collectors.toList()).forEach(v -> System.out.print(v+","));

Find count of all items.


Find count of all distinct items.


Find first element of the list.


Flatten a 2D Array into a 1D Array.

String[][] multiArray = {{"1","2","3"},{"4","5","6"}};

Limit to only x number of elements of the list.;

Create a new stream from the current stream of the list.> v.length()*3).forEach(System.out::print);

Create an Integer stream from a list of Strings. -> v.length()).forEach(w->System.out.print(w*w));

Find max element of the list based on your custom inline comparator.

System.out.println(,b) -> a.length() - b.length()).get());

Find min element of the list based on your custom comparator.

System.out.println(,b) -> a.compareTo(b)).get());

Find if none of the elements in the list matches a given condition.

System.out.println(> a.equals("Anila")));

Skip the first N elements and then perform something.;

Sort the list based on your custom comparator logic.,b) -> a.length()-b.length()).forEach(System.out::print);,b) -> a.compareTo(b)).forEach(System.out::print);


How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Tagged , ,
0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments