1、用户对象
@Getter
@Setter
@AllArgsConstructor
public class UserTest {
// 名称
private String userName;
// 年龄
private string age;
// 分数(这个无所谓啊)
private double score;
}
2、准备数据
List<UserTest> userList = new ArrayList<>();
userList.add(new UserTest("user", "1",3.55));
userList.add(new UserTest("user1", "3",4.66));
userList.add(new UserTest("user2", "2",90.66));
userList.add(new UserTest("user3", "2",7.999));
3、根据年龄分组
Map<Integer, List<UserTest>> groupData = userList.stream()
.collect(Collectors.groupingBy(UserTest::getAge));
结果:
{
"1": [{
"age": "1",
"score": 3.55,
"userName": "user"
}],
"2": [{
"age": "2",
"score": 90.66,
"userName": "user2"
}, {
"age": "2",
"score": 7.999,
"userName": "user3"
}],
"3": [{
"age": "3",
"score": 4.66,
"userName": "user1"
}]
}
4、根据年龄分组、拼按年龄倒序
Map<String, List<UserTest>> groupData = userList.stream()
.collect(
// 根据年龄分组
Collectors.groupingBy(UserTest::getAge,
// 年龄倒序(key)
() -> new TreeMap<>((k1, k2)-> - k1.compareTo(k2)),
Collectors.toList())
);
System.out.println(JSON.toJSONString(groupData));
结果
{
"3": [{
"age": "3",
"score": 4.66,
"userName": "user1"
}],
"2": [{
"age": "2",
"score": 90.66,
"userName": "user2"
}, {
"age": "2",
"score": 7.999,
"userName": "user3"
}],
"1": [{
"age": "1",
"score": 3.55,
"userName": "user"
}]
}
5、根据年龄分组、拼按年龄倒序、value按分数倒序
Map<String, List<UserTest>> groupData = userList.stream()
.collect(
// 根据年龄分组
Collectors.groupingBy(UserTest::getAge,
// 年龄倒序(key)
() -> new TreeMap<>((k1, k2) -> -(k1.compareTo(k2))),
// 分数倒序(value)
Collectors.collectingAndThen(
Collectors.toCollection(
()-> new TreeSet<>(Comparator.comparing(UserTest::getScore,Comparator.reverseOrder())))
,ArrayList::new
)
));
System.out.println(JSON.toJSONString(groupData));
结果:
{
"3": [{
"age": "3",
"score": 4.66,
"userName": "user1"
}],
"2": [{
"age": "2",
"score": 90.66,
"userName": "user2"
}, {
"age": "2",
"score": 7.999,
"userName": "user3"
}],
"1": [{
"age": "1",
"score": 3.55,
"userName": "user"
}]
}
标签:userName,age,userList,score,分组,UserTest,new,排序,java8
From: https://www.cnblogs.com/lcy2020/p/17921270.html