Hot Posts

hot/hot-posts

Java 8 - forEach, Map and Streams


Java 8 introduced the forEach method for iterating over collections, as well as the Stream API for functional-style operations on streams of elements.

Here is an example of using the forEach method to print out the elements of a list:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(System.out::println);

The forEach method takes a single argument, which is a consumer function that is applied to each element of the collection. In this example, we are using a method reference (System.out::println) as the consumer function, which prints out each element of the list.

The map method is used to transform the elements of a stream by applying a function to each element. Here is an example of using the map method to square the elements of a list and collect the results in a new list:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());

In this example, the map method takes a single argument, which is a function that squares its input. The collect method is used to collect the elements of the stream into a new list.

The Stream API also provides many other operations, such as filter, sorted, reduce, and count, which can be used to perform more complex operations on streams.

Here's an example of a stream pipeline that finds all the even numbers in a list and square them, and return the sum of the squares.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.reduce(0, Integer::sum);

In this example, the filter method is used to find all the even numbers in the list, map method square the even numbers, and the reduce method is used to find the sum of the squares.

Post a Comment

0 Comments