JAVA8中lamda表达式对集合的操作

一些自己整理的demo,便于回顾。

1.遍历和处理业务

		List<Integer> listScore = Arrays.asList(5, 20);
		//遍历泛型为基本类型直接用使用接口
        listScore.stream().forEach(System.out::println);
        
        //遍历自定义的类 只能先定义对象student
        list.stream().forEach(student -> System.out.println(student.toString()));
		 //遍历处理多行业务
        list.stream().forEach(student -> {
            String status = student.getScore() < 60 ? ":不合格" : ":合格";
            student.setStatus(status);
        });

2.筛选

		 //筛选60以下为不不及格 用于只有一次判断
        list.stream().filter(student -> (student.getScore() < 60)).forEach(s -> s.setStatus("不及格"));
        //把分数转化成一个新的集合
        List<Integer> listScore = list.stream().map(student -> student.getScore()).collect(Collectors.toList());
        //遍历泛型为基本类型直接用使用接口
        listScore.stream().forEach(System.out::println);
        //把60分以下的转化成一个新集合
        List<Student> dStudent = list.stream().filter(student -> student.getScore() < 60).collect(Collectors.toList());
        System.out.println("***不及格****");
        dStudent.stream().forEach(student -> System.out.println(student.toString()));
             

3.合并+查找

  	    Student stu3 = new Student("haiMianBaby", 90);

        Student stu4 = new Student("paiDaXing", 100);

        List<Student> studentList = Arrays.asList(stu3, stu4);
        //把两个集合汇成一个集合
        List<Student> allStudent = Stream.of(list, studentList).flatMap(students -> students.stream()).collect(Collectors.toList());
        allStudent.stream().forEach(student -> System.out.println(student.toString()));
        //寻找集合中最多对象
        Student highScoreStudent = allStudent.stream().max(Comparator.comparing(student -> student.getScore())).get();

        Student lowScoreStudent = allStudent.stream().min(Comparator.comparing(student -> student.getScore())).get();
        System.out.println("分数最高:" + highScoreStudent.toString());
        System.out.println("分数最低" + lowScoreStudent);

Student类

public class Student {
    private String name;
    private Integer score;
    private String status = "无";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值