lambda表达式处理集合List方法总结

别在遇到循环就是for了,以下这些玩法,让你的代码像诗一样优雅。不在看着像小白写的了,

当你需要list求和时,是否还在这样写?

List<Integer> list = new ArrayList<>();
Integer sum = 0;
for (Integer integer : list) {
    sum+=integer;
}

当你需要判断集合中是否有张三这个人时,是否还在这样写?

List<Student> students = new ArrayList<>();
  boolean isExist = false;
  for (Student student : students) {
      if(student.getName().equals("张三")){
            isExist = true;
            break;
      }
}

今天这些都不会再出现,耐心往下看,看完以后,你以后也别用上面这种写法了行吗?

  • 去重
  • 过滤
  • 抽取
  • 分组
  • 计数
  • 最大值、最小值
  • 平均值
  • 排序
  • 匹配
  • 求和

模拟数据

//模拟数据
@Data
    static class Student{
        //学号
        private Integer no;
        //姓名
        private String name;
        //年龄
        private Integer age;
        //成绩
        private Integer socre;

        public Student(Integer no,String name,Integer age,Integer socre){
            this.no = no;
            this.name = name;
            this.age =  age;
            this.socre =socre;
        }
    }
    public static List<Student> mockdata(){
        List<Student> students = new ArrayList<>();
        Student student1 = new Student(1001,"张三",20,100);
        Student student2 = new Student(1002,"张三",30,80);
        Student student3 = new Student(1003,"李四",25,70);
        Student student4 = new Student(1004,"王五",25,65);
        Student student5 = new Student(1005,"赵六",25,40);
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);
        students.add(student5);
        return students;
    }

根据名称去重数据(去重)

//根据名字去重
List<Student> result = data.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new
));
System.out.println(result.toString());
//输出如下:
[Test.Student(name=张三, age=20, socre=100), Test.Student(name=李四, age=25, socre=70), Test.Student(name=王五, age=25, socre=65), Test.Student(name=赵六, age=25, socre=40)]

根据一定条件筛选数据(过滤)

//20<筛选年龄<30的学生
List<Student> filterResult = data.stream().filter(item -> item.getAge() > 20 && item.getAge() < 30).collect(Collectors.toList());
System.out.println(filterResult);
//输出如下
[Test.Student(name=李四, age=25, socre=70), Test.Student(name=王五, age=25, socre=65), Test.Student(name=赵六, age=25, socre=40)]

(数据抽取)

//转为Map,key为学号,value为Student对象
Map<Integer, Student> studentMap = data.stream().collect(Collectors.toMap(s -> s.getNo(), s -> s));
//转为Map,key为学号,value为分数
Map<Integer, Integer> scoreMap = data.stream().collect(Collectors.toMap(s -> s.getNo(), s -> s.getSocre()));
//转为Set,获取所有的学号
Set<Integer> nameset = data.stream().map(s -> s.getNo()).collect(Collectors.toSet());
//转为List,获取所有的学号
List<Integer> namelist = data.stream().map(s->s.getNo()).collect(Collectors.toList());
System.out.println(studentMap);
System.out.println(scoreMap);
System.out.println(nameset);
System.out.println(namelist);
//输出如下:
{1001=Test.Student(no=1001, name=张三, age=20, socre=100), 1002=Test.Student(no=1002, name=张三, age=30, socre=80), 1003=Test.Student(no=1003, name=李四, age=25, socre=70), 1004=Test.Student(no=1004, name=王五, age=25, socre=65), 1005=Test.Student(no=1005, name=赵六, age=25, socre=40)}
{1001=100, 1002=80, 1003=70, 1004=65, 1005=40}
[1001, 1002, 1003, 1004, 1005]
[1001, 1002, 1003, 1004, 1005]

分组

//分组,根据学生姓名分组
Map<String, List<Student>> groupMap = data.stream().collect(Collectors.groupingBy(Student::getName));
//分组后保持有序
LinkedHashMap<String, ArrayList<Student>> groupMapSort = data.stream().collect(Collectors.groupingBy(Student::getName, LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));
//按学生姓名分组,List存放学号
Map<String, List<Integer>> map1 = data.stream().collect(Collectors.groupingBy(Student::getName, Collectors.mapping(Student::getNo, Collectors.toList())));
//按学生姓名分组,Set存放学号
Map<String, Set<Integer>> map2 = data.stream().collect(Collectors.groupingBy(Student::getName, Collectors.mapping(Student::getNo, Collectors.toSet())));
System.out.println(groupMap);
System.out.println(groupMap);
System.out.println(map1);
System.out.println(map2);
//输出如下:
{李四=[Test.Student(no=1003, name=李四, age=25, socre=70)], 张三=[Test.Student(no=1001, name=张三, age=20, socre=100), Test.Student(no=1002, name=张三, age=30, socre=80)], 王五=[Test.Student(no=1004, name=王五, age=25, socre=65)], 赵六=[Test.Student(no=1005, name=赵六, age=25, socre=40)]}
{李四=[Test.Student(no=1003, name=李四, age=25, socre=70)], 张三=[Test.Student(no=1001, name=张三, age=20, socre=100), Test.Student(no=1002, name=张三, age=30, socre=80)], 王五=[Test.Student(no=1004, name=王五, age=25, socre=65)], 赵六=[Test.Student(no=1005, name=赵六, age=25, socre=40)]}
{李四=[1003], 张三=[1001, 1002], 王五=[1004], 赵六=[1005]}
{李四=[1003], 张三=[1001, 1002], 王五=[1004], 赵六=[1005]}

计数

//计数,根据name分组,并获取每个分组的数量
Map<String, Long> count = data.stream().collect(Collectors.groupingBy(Student::getName, Collectors.counting()));
System.out.println(count);
//输出如下:
{李四=1, 张三=2, 王五=1, 赵六=1}

最大值、最小值

//最小年龄
Integer min = data.stream().mapToInt(Student::getAge).min().getAsInt();
//最大年龄
Integer max = data.stream().mapToInt(Student::getAge).max().getAsInt();
// 最大对象
Student maxObject = data.stream().max(Comparator.comparing(Student::getAge)).get();
// 最小对象
Student minObject = data.stream().min(Comparator.comparing(Student::getAge)).get();
System.out.println(min);
System.out.println(max);
System.out.println(maxObject);
System.out.println(minObject);
//输出如下:
20
30
Test.Student(no=1002, name=张三, age=30, socre=80)
Test.Student(no=1001, name=张三, age=20, socre=100)

平均值

// 年龄平均数
double asDouble = data.stream().mapToLong(Student::getAge).average().getAsDouble();
System.out.println(asDouble);
//输出如下:
25.0

排序

// 对象根据年龄属性升序排序
List<Student> ageAsc = data.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
// 对象根据年龄属性降序排序
List<Student> ageDesc = data.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
// 双字段排序,年龄升序,分数降序
List<Student> ageScoreSort = data.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getSocre).reversed()).collect(Collectors.toList());
System.out.println(ageAsc);
System.out.println(ageDesc);
System.out.println(ageScoreSort);
//输出如下:
[Test.Student(no=1001, name=张三, age=20, socre=100), Test.Student(no=1003, name=李四, age=25, socre=70), Test.Student(no=1004, name=王五, age=25, socre=65), Test.Student(no=1005, name=赵六, age=25, socre=40), Test.Student(no=1002, name=张三, age=30, socre=80)]
[Test.Student(no=1002, name=张三, age=30, socre=80), Test.Student(no=1003, name=李四, age=25, socre=70), Test.Student(no=1004, name=王五, age=25, socre=65), Test.Student(no=1005, name=赵六, age=25, socre=40), Test.Student(no=1001, name=张三, age=20, socre=100)]
[Test.Student(no=1002, name=张三, age=30, socre=80), Test.Student(no=1003, name=李四, age=25, socre=70), Test.Student(no=1004, name=王五, age=25, socre=65), Test.Student(no=1005, name=赵六, age=25, socre=40), Test.Student(no=1001, name=张三, age=20, socre=100)]

匹配

//查找list中是否都是张三
boolean result1 = data.stream().allMatch((s) -> s.getName().equals("张三"));
//查找list中是否有一个是张三
boolean result2 = data.stream().anyMatch((s) -> s.getName().equals("张三"));
//判断list中没有张三
boolean result3 = data.stream().noneMatch((s) -> s.getName().equals("张三"));
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
//输出如下:
false
true
false

求和

//成绩总和
Integer scoreSum = data.stream().mapToInt(Student::getAge).sum();
System.out.println(scoreSum);
//输出如下:
125
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员无名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值