Stream for each java

Java Stream forEach()

Java Stream forEach() method is used to iterate over all the elements of the given Stream and to perform an Consumer action on each element of the Stream.

The forEach() is a more concise way to write the for-each loop statements.

1.1. Method Syntax

The forEach() method syntax is as follows:

void forEach(Consumer action)

Consumer is a functional interface and action represents a non-interfering action to be performed on each element in the Stream. It accepts an input and returns no result.

1.2. Description

  • The forEach() method is a terminal operation. It means that it does not return an output of type Stream .
  • After forEach() is performed, the stream pipeline is considered consumed, and Stream can no longer be used.
  • If we need to traverse the same data source again (the collection backing the Stream), we must return to the data source to get a new stream.
  • For parallel streams, the forEach() operation does not guarantee the order of elements in the stream, as doing so would sacrifice the benefit of parallelism.
  • If the provided Consumer action accesses the shared state between the Stream elements the action is responsible for providing the required synchronization.

2. Stream forEach() Examples

Example 1: Traversing the elements of a Stream and printing them

In this Java example, we are iterating over a Stream of Integers and printing all the integers to the standard output.

List list = Arrays.asList(2, 4, 6, 8, 10); Consumer action = System.out::println; list.stream() .forEach( action );

Note that we can write the above iteration using the enhanced for-loop as well.

Example 2: Traversing the elements in reverse order and printing them

Java example to iterate over stream elements and print them in reverse order.

List list = Arrays.asList(2, 4, 6, 8, 10); list.stream() .sorted(Comparator.reverseOrder()) .forEach(System.out::println);

In this tutorial, we learned to use the forEach() method to iterate through all the elements of a Stream.

Though we can use the enhanced for-each loop for the iteration, the primary difference between the forEach() method and for-each loop is that the for-each loop is an external iterator, whereas the new forEach() method is an internal iterator.

Читайте также:  Пояснение работы парсера

Drop me your questions related to Stream forEach() method in Java Stream API.

Источник

Guide to Java Streams: forEach() with Examples

The forEach() method is part of the Stream interface and is used to execute a specified operation, defined by a Consumer .

The Consumer interface represents any operation that takes an argument as input, and has no output. This sort of behavior is acceptable because the forEach() method is used to change the program’s state via side-effects, not explicit return types.

Therefore, the best target candidates for Consumers are lambda functions and method references. It’s worth noting that forEach() can be used on any Collection .

forEach() on List

The forEach() method is a terminal operation, which means that after we call this method, the stream along with all of its integrated transformations will be materialized. That is to say, they’ll «gain substance», rather than being streamed.

Let’s generate a small list:

List list = new ArrayList(); list.add(1); list.add(2); list.add(3); 

Traditionally, you could write a for-each loop to go through it:

for (Integer element : list) < System.out.print(element + " "); > 

Alternatively, we can use the forEach() method on a Stream :

We can make this even simpler via a method reference:

list.stream().forEach(System.out::println); 

forEach() on Map

The forEach() method is really useful if we want to avoid chaining many stream methods. Let’s generate a map with a few movies and their respective IMDB scores:

Map map = new HashMap(); map.put("Forrest Gump", 8.8); map.put("The Matrix", 8.7); map.put("The Hunt", 8.3); map.put("Monty Python's Life of Brian", 8.1); map.put("Who's Singin' Over There?", 8.9); 

Now, let’s print out the values of each film that has a score higher than 8.4 :

map.entrySet() .stream() .filter(entry -> entry.getValue() > 8.4) .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue())); 
Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9 

Here, we’ve converted a Map to a Set via entrySet() , streamed it, filtered based on the score and finally printed them out via a forEach() . Instead of basing this on the return of filter() , we could’ve based our logic on side-effects and skipped the filter() method:

map.entrySet() .stream() .forEach(entry -> < if (entry.getValue() > 8.4) < System.out.println(entry.getKey() + ": " + entry.getValue()); > > ); 
Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9 

Finally, we can omit both the stream() and filter() methods by starting out with forEach() in the beginning:

map.forEach((k, v) -> < if (v > 8.4) < System.out.println(k + ": " + v); > >); 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9 

forEach() on Set

Let’s take a look at how we can use the forEach method on a Set in a bit more tangible context. First, let’s define a class that represents an Employee of a company:

public class Employee < private String name; private double workedHours; private double dedicationScore; // Constructor, Getters and Setters public void calculateDedication() < dedicationScore = workedHours*1.5; > public void receiveReward() < System.out.println(String .format("%s just got a reward for being a dedicated worker!", name)); > > 

Imagining we’re the manager, we’ll want to pick out certain employees that have worked overtime and award them for the hard work. First, let’s make a Set :

 Set employees = new HashSet(); employees.add(new Employee("Vladimir", 60)); employees.add(new Employee("John", 25)); employees.add(new Employee("David", 40)); employees.add(new Employee("Darinka", 60)); 

Then, let’s calculate each employee’s dedication score:

employees.stream().forEach(Employee::calculateDedication); 

Now that each employee has a dedication score, let’s remove the ones with a score that’s too low:

Set regular = employees.stream() .filter(employee -> employee.getDedicationScore() 60) .collect(Collectors.toSet()); employees.removeAll(regular); 

Finally, let’s reward the employees for their hard work:

employees.stream().forEach(employee -> employee.receiveReward()); 

And for clarity’s sake, let’s print out the names of the lucky workers:

System.out.println("Awarded employees:"); employees.stream().map(employee -> employee.getName()).forEach(employee -> System.out.println(employee)); 

After running the code above, we get the following output:

Vladimir just got a reward for being a dedicated worker! Darinka just got a reward for being a dedicated worker! Awarded employees: Vladimir Darinka 

Side-effects Vs Return Values

The point of every command is to evaluate the expression from start to finish. Everything in-between is a side-effect. In this context, it means altering the state, flow or variables without returning any values.

Читайте также:  Python get host ip address

Let’s take a look at the difference on another list:

List targetList = Arrays.asList(1, -2, 3, -4, 5, 6, -7); 

This approach is based on the returned values from an ArrayList :

long result1 = targetList .stream() .filter(integer -> integer > 0) .count(); System.out.println("Result: " + result1); 

And now, instead of basing the logic of the program on the return type, we’ll perform a forEach() on the stream and add the results to an AtomicInteger (streams operate concurrently):

AtomicInteger result2 = new AtomicInteger(); targetList.stream().forEach(integer -> < if (integer > 0) result2.addAndGet(1); >); System.out.println("Result: " + result2); 

Conclusion

The forEach() method is a really useful method to use to iterate over collections in Java in a functional approach.

In certain cases, they can massively simplify the code and enhance clarity and brevity. In this article, we’ve gone over the basics of using a forEach() and then covered examples of the method on a List , Map and Set .

We’ve covered the difference between the for-each loop and the forEach() , as well as the difference between basing logic on return values versus side-effects.

Источник

Java 8 Streams — Stream.forEach Examples

Stream.forEach(Consumer), IntStream.forEach(Consumer), LongStream.forEach(LongConsumer), DoubleStream.forEach(DoubleConsumer), all these terminal operations allow client code to take consumer actions on each element of this stream. These methods do not respect the encounter order, whereas, Stream .forEachOrdered(Consumer), LongStream.forEachOrdered(LongConsumer), DoubleStream .forEachOrdered(DoubleConsumer) methods preserve encounter order but are not good in performance for parallel computations.

package com.logicbig.example;

import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class ForEachExample
public static void main (String[] args) final int[] ints = IntStream.range(0, 5).toArray();
PerformanceTestUtil.runTest("forEach() method", () -> Arrays.stream(ints).parallel().forEach(i -> doSomething(i));
>);

PerformanceTestUtil.runTest("forEachOrdered() method", () -> Arrays.stream(ints).parallel().forEachOrdered(i -> doSomething(i));
>);
>

private static void doSomething (int i) try Thread.sleep(10);
> catch (InterruptedException e) e.printStackTrace();
>
System.out.printf("%s, ", i);
>
>

Output

3, 2, 0, 4, 1, forEach() method time taken: 15.41 milliseconds
0, 1, 2, 3, 4, forEachOrdered() method time taken: 77.55 milliseconds

package com.logicbig.example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class SideEffectWrongUse
public static void main (String[] args) List results = new ArrayList<>();
IntStream.range(0, 150)
.parallel()
.filter(s -> s % 2 == 0)
.forEach(s -> results.add(s));//stateful side effect
//not thread safe
System.out.println(results);
>
>

Output

[98, 100, 94, 96, 108, 110, 102, 104, 106, 84, 86, 88, 90, 92, 80, 82, 76, 78, 22, 24, 26, 46, 48, 50, 18, 20, 52, 54, 32, 42, 34, 44, 36, 38, 28, 40, 30, 66, 68, 10, 12, 70, 72, 14, 74, 16, 60, 4, 62, 6, 64, 8, 56, 0, 58, 2, 126, 116, 118, 128, 120, 130, 136, 138, 112, 122, 146, 114, 124, 148, 132, 134, 140, 142, 144]

private static void printMap (Map map) map.entrySet() 
.stream().limit(15)
.forEach(e -> System.out.println(e.getKey() + " -------------");

>

Источник

Оцените статью