Reference: http://www.mkyong.com/java8/java-8-foreach-examples/
/*
Java8 中使用forEach + lambda expression/method reference 循环列表
*/
import java.util.ArrayList;
import java.util.List;
public class Exercise {
public static void main(String args[]) {
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
// Normal for-loop to loop a list
for (String item: items){
System.out.println(item);
}
// lambda expression
// output A B C
items.forEach(item -> System.out.println(item));
// output C
items.forEach(item -> {
if ("C".equals(item)){
System.out.println(item);
}
});
// method reference
// output A B C (color red)
items.forEach(System.err::println);
// Stream and filter
// output B
items.stream().filter(s -> s.contains("B")).
forEach(System.out::println);
}
}
/*
Java8 中使用forEach + lambda expression/method reference 循环Map
*/
import java.util.HashMap;
import java.util.Map;
public class Exercise {
public static void main(String args[]) {
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 60);
// normal for loop
System.out.println("Normal for loop: ");
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println("Item: " + entry.getKey() +"\t"+ "Count: " + entry.getValue());
}
// In Java8, we can loop a Map with forEach + lambda expression
System.out.println("forEach + lambda expression: ");
items.forEach((k, v) -> System.out.println("Item: " + k +"\t"+ "Count: " + v));
// witr if condition
System.out.println("If condition");
items.forEach((k, v) -> {
if ("A".equals(k)) {
System.out.println(k);
}
});
}
}