Java Lambda表达式示例(偶尔更新)

1,958 阅读1分钟

Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。 Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。 使用 Lambda 表达式可以使代码变的更加简洁紧凑。

一、利用流和Lambda表达式对List集合进行处理

1.List集合遍历

// item:可以是任意值。类似于for循环中的循环值
   dataList.forEach(item -> {
              //设置值
             item.setName(item.getName()+"测试");;
             //输出语句
             System.out.println(item.toString());  
                });
            }

2.统计List集合

sum(),max(),min(),average() 。

mapToInt() 转换成int。还有其他类型转换。如:double。

 int rowCount = list.stream().mapToInt(Paper::getRow).sum();

3.对List集合分组

Collectors.groupingBy(属性名)

 Map<Integer, List<Product>> map = list.stream().collect(Collectors.groupingBy(Product::getType));

4.多重分组

Collectors.groupingBy(属性,Collectors.groupingBy(属性))

         Map<String, Map<Integer, List<Product>>> map2 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getType())));

5.map(), 提取对象中的某一元素. 用每一项来获得属性(也可以直接用 对象::get属性())

        List<String> mapList1 = list.stream().map(Product::getName).collect(Collectors.toList());
         List<String> mapList2 = list.stream().map(item->item.getName()).collect(Collectors.toList());

6.过滤

filter(item->{}) item为每一项。 按照自己的需求来筛选list中的数据

       List<Person> filterList = list.stream().filter(item->item.getPrice()>100).collect(Collectors.toList());

7. 去重

distinct() 去重;collect(Collectors.toList())。封装成集合

List<Product> distinctList = list.stream().distinct().collect(Collectors.toList());

8.List对象中的属性以逗号分隔转字符串

String names = testDemos.stream().map(TestDemo::getName).collect(Collectors.joining(","));

9. 把一个对象list的元素放到另外一个list

list2 = list1.stream().map(user->{return user.getRealName();}).collect(Collectors.toList());

10.将对象list中的属性转换为Map键值对

Map<String, String> educationMap = educationList.stream().collect(Collectors.toMap(SystemOption::getName, b -> b.getCode(), (k1, k2) -> k1));

当toMap的时候List中存在相同的条件时,最后一个参数 (k1, k2) -> k1) 可选择用k1还是k2,或者重写该接口

(k1, k2) -> {
            if ("1".equals(k1) || "1".equals(k2)) {
                return "1";
            } else {
                return "0";
            }
        }

11.对象list求和

Double count = list.stream().mapToDouble(CreditFractionRecord::getFr_score).sum();

12.将对象list中的转换为Map<id,对象>

Map<Long, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getId, (k) -> k));