Java-Stream sorted 排序

sorted 方法用于元素排序

一、升序

List<userInfo> userList = new ArrayList<>();
// userInfo字段 UserId; Age; NickName; Sex 1:男  2:女;  moneny零花钱
userList.add(new userInfo(1,24,"小明",1,new BigDecimal("11")));
userList.add(new userInfo(2,22,"小红",2,new BigDecimal("22")));
userList.add(new userInfo(3,24,"小张",1,new BigDecimal("33")));


List<Integer> integers = Arrays.asList(1, 2, 3, 4);

//年龄升序
List<userInfo> userList1 = userList.stream()
				.sorted(Comparator.comparing(userInfo::getAge))
				.collect(Collectors.toList());

List<Integer> filter1 = integers.stream()
				.sorted(Comparator.comparing(Integer::intValue))
				.collect(Collectors.toList());



二、降序 reversed

List<userInfo> userList2 = userList.stream()
			.sorted(Comparator.comparing(userInfo::getAge).reversed())
			.collect(Collectors.toList());

List<Integer> filter2 = integers.stream()
			.sorted(Comparator.comparing(Integer::intValue).reversed())
			.collect(Collectors.toList());



三、多字段排序

关键字thenComparing

1.先以年龄升序
2.当年龄相同时,在以零花钱升序

List<userInfo> userList3 = userList.stream()
	.sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney))
	.collect(Collectors.toList());



四、多字段区分升序降序

关键字thenComparing、Comparator.reverseOrder()

1.先以年龄升序
2.当年龄相同时,在以零花钱降序 Comparator.reverseOrder()

List<userInfo> userList3 = userList.stream()
			.sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney,Comparator.reverseOrder()))
			.collect(Collectors.toList());

Java-Stream sorted 排序_第1张图片

你可能感兴趣的:(Java)