java8的lambda过滤list遍历集合,排序
1.根据属性过滤list
List<AllManagerBean> testLists = broadCastRoomMapper.allManagerlist();
List<AllManagerBean> mans = testLists.stream().filter(j->j.getRoomId().equals(roomid)).collect(Collectors.toList());
//过滤某一属性,成一个新集合
List<String> uids = testLists.stream().map(e->e.getUserid()).collect(Collectors.toList());
2.遍历集合
List<ManagerBean> managerListNew = new ArrayList<ManagerBean>();
if (mans != null ){
mans.forEach(man->{
managerListNew.add(man);
});
}
3.根据某一集合对象中的某一属性,排序
List<Model> thlistbysort = thlist.stream().sorted(Comparator.comparing(Model::getSort)).collect(Collectors.toList()); //正序
List<Model> thlistbysort = thlist.stream().sorted(Comparator.comparing(Model::getSort).reversed()).collect(Collectors.toList()); //倒序
4.对List<String>进行正序,倒序排列
//正序排列
Collections.sort(s);
//倒序排列(先对list正序排列,然后反向排序)
Collections.sort(s);
Collections.reverse(s);//反向排序
5.转成setSet<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
6.转成map,注:key不能相同,否则报错
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge)); // {cc=10, bb=20, aa=10}
7.字符串分隔符连接
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
8.查询总数
Long count = list.stream().collect(Collectors.counting());
9.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); /
10.所有人的年龄
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge));
11.平均年龄
Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge));
12.带上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
13.分组
Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
14.多重分组,先根据类型分再根据年龄分
Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
15.分区
//分成两部分,一部分大于10岁,一部分小于等于10岁
Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
16.规约
Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40
原创博客,引用请注明出处 https://www.cnblogs.com/guangxiang/p/11077860.html