本文為博主原創,未經允許不得轉載
對應實體類
importlombok.Getter;importlombok.Setter;
@Getter
@Setterpublic classStudent {privateString name;private intage;privateString className;privateString birthday;
}
1.根據字段取出某一個字段屬性的集合
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根據某個字段升序排序
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根據某個字段排序降序
List list = new ArrayList<>();
list= list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
4.獲取某一字段屬性值對應的數據集合
List resultList =studentList.stream()
.filter((Student stu)->area.equals(stu.getAge()))
.collect(Collectors.toList());
5.根據某個字段值獲取出對應的對象
Student stu =studentList.stream()
.filter(p-> "2018-08-12 12:10".equals(p.getBirthday()))
.findAny().orElse(null);
6.對集合元素去重
List nameList = new ArrayList<>();
nameList= nameList.stream().distinct().collect(Collectors.toList());
7.對集合某一個屬性進行求和
List stuList = new ArrayList<>();double totalAge = stuList.stream().collect(Collectors.summingDouble(Student::getAge));
8。獲取集合中的某一個屬性的數據集合并去重
// 所有的ip信息對象集合
List netInfoList =netIpService.queryNetIpList();
// 從所有IP信息對象集合中根據機房id過濾出所有機房id不同的數據對象,并根據機房id去重
List distinctIpRoomList =netInfoList.stream().collect(Collectors
.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(
Comparator.comparing(NetiIpInfo::getIpRoomId))), ArrayList::new));
代碼是很簡答,很優雅的
解釋一下
list.stream(): 是把list集合轉化為stream集合
sorted(): 進行排序,其中Comparator.comparing(Student::getAge)表示按照年紀排序,
.reversed()表示是逆序,因為默認情況下,不加.reversed 是升序的
collect(Collectors.toList()): 再次將排序后的stream集合轉化為list集合
.findAny()表示將其中任意一個返回;
.orElse(null)表示如果一個都沒找到返回null
distinct() 對集合元素或對象去重
summingDouble() 對集合元素進行求和為double類型數據