servlets struts hibernate jsf spring maven
 

Java 8 forEach


The Java forEach is an utility strategy to repeat over a gathering or stream and play out a specific activity on every component of it.

Java 8 forEach method

Below code bit demonstrates the default usage of java forEach technique in Iterable interface. It makes this technique accessible to all gathering classes with the exception of Map.

The strategy plays out the given activity for every component of the Iterable until the sum total of what components have been prepared or the activity tosses an exception.

default void forEach(Consumer<? super T> activity) { 

Objects.requireNonNull(action); 

for (t : this) { 

action.accept(t); 

} 

} 

A custom activity can be made utilizing this straightforward sentence structure. Here Object type will be supplanted with the sort of components in the gathering or stream.

Consumer<Object> activity = new Consumer<Object>() 

{ 

@Override 

open void accept(Object t) 

{ 

/perform activity 

} 

}; 

Java 8 stream forEach example

Java program to emphasize over all components of a stream and play out an activity. In this precedent, we are printing all even numbers.

ArrayList<Integer> numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5)); 

Consumer<Integer> activity = System.out::println; 

numberList.stream().filter(n - > n%2 == 0).forEach( activity ); 

Run model ยป

Java forEach model utilizing List

Java program to repeat over all components of an arraylist and play out an activity. Here activity is as basic as printing out the component in console.

ArrayList<Integer> numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5)); 

Consumer<Integer> activity = System.out::println; 

numberList.forEach(action); 

Program yield.
1 

2 

3 

4 

5 

Java forEach model utilizing Map

Java program to repeat over all passages of and play out an activity. We can likewise emphasize over guide keys and values and play out any activity on all elements.

HashMap<String, Integer> map = new HashMap<>(); 

map.put("A", 1); 

map.put("B", 2); 

map.put("C", 3); 

/1. Guide sections 

Consumer<Map.Entry<String, Integer>> activity = System.out::println; 

map.entrySet().forEach(action); 

/2. Guide keys 

Consumer<String> actionOnKeys = System.out::println; 

map.keySet().forEach(actionOnKeys); 

/3. Guide esteems 

Consumer<Integer> actionOnValues = System.out::println; 

map.values().forEach(actionOnValues); 

yield
A=1 

B=2 

C=3 

A 

B 

C 

1 

2 

3 






javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition

JAVACODEGEEKS
EmberJS Tutorial