package com.config;
import java.util.ArrayList;
import java.util.List;
/**
-
for循环遍历之Lambda表达式遍历
*/
public class List2Lambda {
public static void main(String[] args) {
List items = new ArrayList<>();items.add("Apple"); items.add("Pear"); items.add("Carambola"); // 普通for循环遍历 System.out.println("1:普通for循环遍历"); for (int i = 0; i < items.size(); i++) { System.out.println(items.get(i)); } // 增强for循环遍历 System.out.println("\n2:增强for循环遍历"); for (String item : items) { System.out.println(item); } // Lambda 表达式遍历(JDK 1.8) System.out.println("\n3:Lambda表达式遍历"); items.forEach(item->{ System.out.println(item); }); // Lambda 表达式遍历(JDK 1.8) System.out.println("\n4:Lambda 表达式遍历"); items.forEach(System.out::println); // 普通for循环遍历,判断List集合中是否包含字符串“C” System.out.println("\n1:普通for循环遍历,判断List集合中是否包含字符串Apple"); for (int i = 0; i < items.size(); i++) { if (items.get(i).equals("Apple")){ System.out.println(items.get(i)); } } // 增强for循环遍历,判断List集合中是否包含字符串“C” System.out.println("\n2:增强for循环遍历,判断List集合中是否包含字符串Apple"); for (String item : items) { if(item.equals("Apple")){ System.out.println(item); } } // Lambda 表达式 判断List集合中是否包含字符串“C”(JDK 1.8) System.out.println("\n3:Lambda 表达式,判断List集合中是否包含字符串Apple"); items.forEach(item->{ if(item.equals("Apple")){ System.out.println(item); } }); // Lambda 表达式 判断List集合中是否包含字符串“C”(JDK 1.8) System.out.println("\n4:Lambda 表达式,判断List集合中是否包含字符串Apple"); items.stream().filter(s->s.equals("Apple")).forEach(System.out::println);
}
}
执行效果:
1:普通for循环遍历
Apple
Pear
Carambola
2:增强for循环遍历
Apple
Pear
Carambola
3:Lambda表达式遍历
Apple
Pear
Carambola
4:Lambda 表达式遍历
Apple
Pear
Carambola
1:普通for循环遍历,判断List集合中是否包含字符串Apple
Apple
2:增强for循环遍历,判断List集合中是否包含字符串Apple
Apple
3:Lambda 表达式,判断List集合中是否包含字符串Apple
Apple
4:Lambda 表达式,判断List集合中是否包含字符串Apple
Apple