记录一下最近工作中使用到的一些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); }
运行结果:
等待后续。。。。。