JDK8 foreach案例测试

/ Java / 0 条评论 / 1163 浏览

@org.junit.Test public void test() { //list遍历案例 List strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei"); //遍历方法一 strList.forEach(x -> { System.out.println(x); }); //遍历方法二 strList.forEach((x2) -> { System.out.println(x2); }); //遍历方法三 strList.forEach(System.out::println); //匹配字符"YangHang" strList.forEach(item ->{ if ("YangHang".equalsIgnoreCase(item)){ System.out.println(item); } });

//Map遍历案例
 Map<String,User> map =new HashMap<>();
    map.put("1",new User("aa",10));
    map.put("2",new User("bb",11));
    map.put("3",new User("cc",12));

    //匹配输出,匹配项可以为list集合元素的属性(成员变量)
    map.forEach((t,v)->System.out.println("id : " + t + " User : " + v));