Member-only story

Java8 Map, Filter and Reduce methods

Gain Java Knowledge
2 min readJul 17, 2021

--

How to use map(), filter() and reduce() methods on java8 stream.

map(), reduce() and filter() are intermediate operations to transforming and filtering the elements. With these three methods we can do a lot, so its worth knowing them intimately.

These three methods we can apply only on stream. In our last article, we have already discussed about Stream in java. So once you have a stream object, you can use variety of methods to transform it into another stream object.

1. Map():
=====

In simple words, the map() method is used to transform one object into another object. It takes a lambda expression as its only argument, ang uses it to change every individual element in the stream.
Its return value is a new stream object containing the changed elements.

String[] nameArrays = new String[] { “abc”, “karan”, “mohit”, “vivek” };
String[] newArray = Arrays.stream(nameArrays).map(name -> name.toUpperCase()).toArray(String[]::new);

So this is the example of map() method that is used to convert all elements into upperCase.

2. Filter():
======

The filter() method as its name suggests, filter elements based upon a condition you gave it.
As we saw map() method process every single element in a stream object. Sometime there is a requirement you might not always want to process each element. To do so, you can use the filter method. Just like map() method, the…

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet