专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

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

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));

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));

文章永久链接:https://tech.souyunku.com/47545

未经允许不得转载:搜云库技术团队 » Java Lambda表达式示例(偶尔更新)

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们