pojo类中list存储其他字段_List集合流处理类型小结
本文為博主原創(chuàng),未經(jīng)允許不得轉(zhuǎn)載
對(duì)應(yīng)實(shí)體類
importlombok.Getter;importlombok.Setter;
@Getter
@Setterpublic classStudent {privateString name;private intage;privateString className;privateString birthday;
}
1.根據(jù)字段取出某一個(gè)字段屬性的集合
List studentList = new ArrayList<>();
List newList =studentList.stream().map(Student::getAge).collect(Collectors.toList());for(Student student : newList) {
System.out.println(student.getName()+"---"+student.getAge());
}
2。List根據(jù)某個(gè)字段升序排序
List studentList = new ArrayList<>();
List newList =studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());for(Student student : newList) {
System.out.println(student.getName()+"---"+student.getAge());
}
3.List根據(jù)某個(gè)字段排序降序
List list = new ArrayList<>();
list= list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
4.獲取某一字段屬性值對(duì)應(yīng)的數(shù)據(jù)集合
List resultList =studentList.stream()
.filter((Student stu)->area.equals(stu.getAge()))
.collect(Collectors.toList());
5.根據(jù)某個(gè)字段值獲取出對(duì)應(yīng)的對(duì)象
Student stu =studentList.stream()
.filter(p-> "2018-08-12 12:10".equals(p.getBirthday()))
.findAny().orElse(null);
6.對(duì)集合元素去重
List nameList = new ArrayList<>();
nameList= nameList.stream().distinct().collect(Collectors.toList());
7.對(duì)集合某一個(gè)屬性進(jìn)行求和
List stuList = new ArrayList<>();double totalAge = stuList.stream().collect(Collectors.summingDouble(Student::getAge));
8。獲取集合中的某一個(gè)屬性的數(shù)據(jù)集合并去重
// 所有的ip信息對(duì)象集合
List netInfoList =netIpService.queryNetIpList();
// 從所有IP信息對(duì)象集合中根據(jù)機(jī)房id過濾出所有機(jī)房id不同的數(shù)據(jù)對(duì)象,并根據(jù)機(jī)房id去重
List distinctIpRoomList =netInfoList.stream().collect(Collectors
.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(
Comparator.comparing(NetiIpInfo::getIpRoomId))), ArrayList::new));
代碼是很簡答,很優(yōu)雅的
解釋一下
list.stream(): 是把list集合轉(zhuǎn)化為stream集合
sorted(): 進(jìn)行排序,其中Comparator.comparing(Student::getAge)表示按照年紀(jì)排序,
.reversed()表示是逆序,因?yàn)槟J(rèn)情況下,不加.reversed 是升序的
collect(Collectors.toList()): 再次將排序后的stream集合轉(zhuǎn)化為list集合
.findAny()表示將其中任意一個(gè)返回;
.orElse(null)表示如果一個(gè)都沒找到返回null
distinct() 對(duì)集合元素或?qū)ο笕ブ?/p>
summingDouble() 對(duì)集合元素進(jìn)行求和為double類型數(shù)據(jù)
總結(jié)
以上是生活随笔為你收集整理的pojo类中list存储其他字段_List集合流处理类型小结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奥哲徐平俊:乘风、冒险与未来
- 下一篇: Vi编辑器介绍