Loading

记录一下最近工作中使用到的一些stream用法

一.准备

实体类:

复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Stu {

    private Integer cid;
    private Integer id;
    private String name;
    private Integer aScore;
    private Integer bScore;
    private Integer dScore;

}
复制代码

vo类:

  @Data
    public class Vo{
        private Integer cid;
        private Integer aScore;
        private Integer bScore;
        private Integer cScore;
    }

集合:

    Stu stu1 = new Stu(1,1,"张飞",50,24,33);
    Stu stu2 = new Stu(1,2,"王飞",50,24,12);
    Stu stu3 = new Stu(1,3,"李飞",30,34,33);
    Stu stu4 = new Stu(2,4,"李飞",60,1,67);
    Stu stu5 = new Stu(2,5,"张飞",70,77,32);
    List<Stu> stus = Arrays.asList(stu1,stu2,stu3,stu4,stu5);

二:希望Stu按cid分组,然后求得分组后,所有分数的总和,并封装到Vo中,返回一个VoList

复制代码
    @Test
    public void test(){
        //public Stu(Integer cid, Integer id, String name, Integer aScore, Integer bScore, Integer dScore) {
        //希望Stu按cid分组,然后求得分组后,所有分数的总和,并封装到Vo中,返回一个VoList
        Map<Integer, List<Stu>> collect = stus.stream().collect(Collectors.groupingBy(Stu::getCid));
        List<Vo> vos = collect.values().stream().map((List<Stu> stuList) -> {
            Vo vo = new Vo();
            vo.setCid(stuList.get(0).getCid());
            vo.setAScore(stuList.stream().map(Stu::getAScore).reduce(Integer::sum).get());
            vo.setBScore(stuList.stream().map(Stu::getBScore).reduce(Integer::sum).get());
            vo.setCScore(stuList.stream().map(Stu::getDScore).reduce(Integer::sum).get());
            return vo;
        }).sorted(Comparator.comparing(Vo::getBScore).reversed()).collect(Collectors.toList());

        System.out.println(vos);
    }
复制代码

运行结果:

 

 三.对对象进行去重,去重条件是对象的某一属性

复制代码
    @Test
    public void test2(){
        //希望对stus这一集合进行去重,去重条件是根据Stu的Name属性
        List<Stu> s = stus.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(Stu::getName))), ArrayList::new));
    s.forEach(System.out::println);
}
复制代码

运行结果:

 

 四:无法描述

复制代码
@Test
    public void test3(){
        //希望获取一个map,key是stu的id,value是A分数和B分数的List
        Map<Integer,List<Integer>> scoreMap = stus.stream().collect(Collectors.toMap(Stu::getId,stu->{
            List<Integer> scores = new ArrayList<>();
            scores.add(stu.getAScore());
            scores.add(stu.getBScore());
            return scores;
        }));
        System.out.println(scoreMap);
    }
复制代码

运行结果:

 

 等待后续。。。。。

posted @   秋风飒飒吹  阅读(270)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示