Search⌘ K
AI Features

For Each and Map/Reduce

Explore how to apply Java 8's forEach, map, and reduce methods to process collections more effectively. Learn to replace traditional loops with streams, perform filtering, mapping, and aggregate operations, and find highest values in datasets using functional programming concepts.

We'll cover the following...

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:

Java
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:

Java
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 ...