I have already covered normal way of iterating Map and list in Java. In this tutorial, we will see how to iterate (loop) Map and List in Java 8 using Lambda expression.
Iterating Map in Java 8 using Lambda expression
package com.beginnersbook;
import java.util.HashMap;
import java.util.Map;
public class IterateMapUsingLambda {
public static void main(String[] args) {
Map<String, Integer> prices = new HashMap<>();
prices.put("Apple", 50);
prices.put("Orange", 20);
prices.put("Banana", 10);
prices.put("Grapes", 40);
prices.put("Papaya", 50);
/* Iterate without using Lambda
for (Map.Entry<String, Integer> entry : prices.entrySet()) {
System.out.println("Fruit: " + entry.getKey() + ", Price: " + entry.getValue());
}
*/
prices.forEach((k,v)->System.out.println("Fruit: " + k + ", Price: " + v));
}
}
Output:
Fruit: Apple, Price: 50 Fruit: Grapes, Price: 40 Fruit: Papaya, Price: 50 Fruit: Orange, Price: 20 Fruit: Banana, Price: 10
Iterating List in Java 8 using Lambda expression
package com.beginnersbook;
import java.util.List;
import java.util.ArrayList;
public class IterateListUsingLambda {
public static void main(String[] argv) {
List names = new ArrayList<>();
names.add("Ajay");
names.add("Ben");
names.add("Cathy");
names.add("Dinesh");
names.add("Tom");
/* Iterate without using Lambda
Iterator iterator = names.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
*/
names.forEach(name->System.out.println(name));
}
}
Output:
Ajay Ben Cathy Dinesh Tom
SRIKANTH says
can you explain lamda expressions ?
Subbiah S says
Please go through this
https://beginnersbook.com/2017/10/java-lambda-expressions-tutorial-with-examples/