...

/

For Each and Map/Reduce

For Each and Map/Reduce

Learn about the `forEach` and map/reduce method in Java 8.

For each

The most basic thing we can do with a stream is loop through it using the forEach method.

For example, to print out all of the files in the current directory, we could do the following:

Press + to interact
Program.java
Helloworld
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.File;
import java.io.IOException;
public class Program{
public static void main(String[] args)throws IOException{
Files.list(Paths.get("."))
.forEach(System.out::println);
}
}

For the most part, this replaces the for loop. It is more concise and more object-oriented since we are delegating the implementation of the actual loop.

Map, filter, and reduce

Lambda expressions and default methods allow us to implement map/filter/reduce in Java 8. Actually, it is already implemented for us in the standard library.

Let’s see how these methods can be implemented:

Press + to interact
import java.util.*;
class Mapexample {
public static void main(String args[]) {
Map < String, Integer > map = new HashMap < String, Integer > ();
map.put("Hello", 23);
map.put("Gary", 123);
map.put("Larry", 145);
//Elements can traverse in any order
for (Map.Entry m: map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}

The above program creates a map with ...

Access this course and 1200+ top-rated courses and projects.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy