Java 8 forEach简单例子
1.遍历map
void testMap() { Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 1); map.put("c", 1); map.forEach((k, v)-> System.out.println(k + ":" + v)); }
输出
a:1 b:1 c:1
2.遍历带lambda条件的map
void testMapLambda() { Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 1); map.put("c", 1); map.forEach((k, v)-> { if ("b".equalsIgnoreCase(k)) { System.out.println(k + ":" + v); } }); }
输出
b:1
3.遍历带lambda条件的list
void testList() { List<String> list = new ArrayList<>(); list.add("abc"); list.add("def"); list.add("hij"); list.forEach(key -> { if ("def".equalsIgnoreCase(key)) { System.out.println(key); } } ); }
输出
def
Lambda表达式局部变量
示例
public class LambdaTest { int instanceCounter = 0; public void method() { int localCounter = 0; instanceCounter = 5; //Re-assign instance counter so it is no longer effectively final Stream.of(1,2,3).forEach(elem -> instanceCounter++); //WHY DOES THE COMPILER NOT COMPLAIN HERE Stream.of(1,2,3).forEach(elem -> localCounter++); //Does not compile because localCounter is not effectively final } }
其中instanceCounter是类的成员变量,localCounter是函数的局部变量,在标红的语句报错
Variable used in Lambda expression must be final or effectively final