Java中数组和集合使用forEach和lambda表达式的区别

    xiaoxiao2023-10-25  160

    1. 数组中使用forEach和lambda表达式

    数组不能直接在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);

    2. 集合中使用forEach和lambda表达式

    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()));
    最新回复(0)