数组不能直接在forEach中使用lambda表达式,必须做如下转换后才能使用:
String[] strArr = new String[3]; strArr[0] = "a"; strArr[1] = "b"; strArr[2] = "c"; // 错误使用 // 提示Cannot resolve method 'forEach(<method reference>) strArr.forEach(System.out::println);1) 转成list
// 转成list Arrays.asList(values).forEach(System.out::println);2) 转成steam
// 转成流 Arrays.stream(values).forEach(System.out::println);1) 在list中使用forEach和lambda表达式:
ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.forEach(System.out::println);2)在map中使用forEach和lambda表达式:
HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("a",1); hashMap.put("b",2); hashMap.put("c",3); hashMap.put("d",4); hashMap.forEach((k,v)->System.out.println(k+"_"+v.intValue()));