1、分组并且求取每个分组的个数
List<TestEntity> list = ListUtil.toList(new TestEntity("1", "小李", 18), new TestEntity("2", "小王", 17), new TestEntity("2", "小屁", 17), new TestEntity("2", "小屁zhu", 17) ); Map<Integer, Long> groupBy = list.stream().collect(Collectors.groupingBy(TestEntity::getAge, Collectors.counting())); System.out.println(JSONObject.toJSONString(groupBy));
执行结果:{17:3,18:1}
2、map、peek和forEach
2.1、map:用于对流中的每个元素进行映射处理,然后再形成新的流
List<AlsRankingList>list= alsRankingLists.stream().map(alsRankingList -> { alsRankingList.setListId(param.getListId()); alsRankingList.setSettingId(param.getSettingId()); return alsRankingList; } ).collect(Collectors.toList());
2.2、peek:用于 debug 调试流中间结果,不能形成新的流,但能修改引用类型字段的值
alsRankingLists = alsRankingLists.stream().peek(alsRankingList -> { alsRankingList.setListId(param.getListId()); alsRankingList.setSettingId(param.getSettingId()); } ).collect(Collectors.toList());
2.3、foreach:用于遍历,会中断流操作
list.forEach(a-> { a.setExamineeMark(BigDecimal.ZERO); });
3、join拼接字符串
String str = bpiGradegroup.getBpiGradeList().stream().map(s -> '【' + s.getGrade() + '】').collect(Collectors.joining(","));
输出结果【初一】,【初二】,【初三】
或者
String str = bpiGradegroup.getBpiGradeList().stream().map(s -> '”' + s.getGrade() + '”').collect(Collectors.joining(",", "【", "】"));
输出结果【”初一”,”初二”,”初三”,”初四”】
4、返回第一条数据
List<TestEntity> list = ListUtil.toList(new TestEntity("1", "小李", 18), new TestEntity("2", "小王", 17), new TestEntity("3", "小屁", 17), new TestEntity("4", "小屁zhu", 17) ); TestEntity testEntity = list.stream().findFirst().get(); System.out.println("返回第一个数据:"+JSON.toJSONString(testEntity)); 返回第一个数据:{"age":18,"id":"1","name":"小李"}
5、是否存在年龄大于17的人
List<TestEntity> list = ListUtil.toList(new TestEntity("1", "小李", 18), new TestEntity("2", "小王", 17), new TestEntity("3", "小屁", 16), new TestEntity("4", "小屁zhu", 18) ); boolean allPositive = list.stream() .anyMatch(n -> n.getAge() > 17); System.out.println("是否存在年龄大于17的人:"+allPositive); 是否存在年龄大于17的人:true
6、所有人是否年龄都大于17
List<TestEntity> list = ListUtil.toList(new TestEntity("1", "小李", 18), new TestEntity("2", "小王", 17), new TestEntity("3", "小屁", 16), new TestEntity("4", "小屁zhu", 18) ); boolean allPositive = list.stream() .allMatch(n -> n.getAge() > 17); System.out.println("是否所有人年龄都大于17:"+allPositive); 是否所有人年龄都大于17:false
7、是否所有人年龄都小于18
List<TestEntity> list = ListUtil.toList(new TestEntity("1", "小李", 18), new TestEntity("2", "小王", 17), new TestEntity("3", "小屁", 16), new TestEntity("4", "小屁zhu", 18) ); boolean noneNegative = list.stream() .noneMatch(n -> n.getAge() < 18); System.out.println("是否所有人年龄都小于18:"+noneNegative); 是否所有人年龄都小于18:false
8、string[]转list<>
String[] idStr = {"1", "2", "3", "4", "5"}; List<Long> ids = Arrays.stream(idStr) .map(Long::parseLong) .collect(Collectors.toList()); System.out.println(ids);