话不多说,直接上需求,一个简简单单的需求
@Data
@Accessors(chain = true)
static
class Person {
private String name;
private Integer age;
}
public static void main(String[] args) {
//
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("idle", "2022-03-03");
map1.put("person", new Person().setName("test1").setAge(30));
Map<String, Object> map2 = new HashMap<>();
map2.put("idle", "2024-04-04");
map2.put("person", new Person().setName("test2").setAge(50));
Map<String, Object> map3 = new HashMap<>();
map3.put("idle", "2023-04-04");
map3.put("person", new Person().setName("test3").setAge(60));
Map<String, Object> map4 = new HashMap<>();
map4.put("idle", "2023-04-04");
map4.put("person", new Person().setName("test4").setAge(50));
Map<String, Object> map5 = new HashMap<>();
map5.put("idle", "2023-04-04");
map5.put("person", new Person().setName("test5").setAge(55));
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
list.forEach(l -> log.info("{}", l));
}
现在我想将list继续排序,要求是先按照idle升序,如果idle一样,按照Person的age升序,如果没进行排序,上面代码main方法执行后结果如下:
{idle=2022-03-03, person=MyTest.Person(name=test1, age=30)}
{idle=2024-04-04, person=MyTest.Person(name=test2, age=50)}
{idle=2023-04-04, person=MyTest.Person(name=test3, age=60)}
{idle=2023-04-04, person=MyTest.Person(name=test4, age=50)}
{idle=2023-04-04, person=MyTest.Person(name=test5, age=55)}
现在进行排序,在main方法中继续追加如下代码:
log.info("=============================================== 开始排序, idele升序, idle相同的age升序");
list = list.stream().sorted(
// 使用(Function<Map<String, Object>, String>)强转的原因是类型转换失败问题
Comparator.comparing((Function<Map<String, Object>, String>) map -> (String) map.get("idle"))
.thenComparing(map -> {
final Person person = (Person) map.get("person");
return person.getAge();
})
).collect(Collectors.toList());
list.forEach(l -> log.info("{}", l));
再次执行main方法:
{idle=2022-03-03, person=MyTest.Person(name=test1, age=30)}
{idle=2024-04-04, person=MyTest.Person(name=test2, age=50)}
{idle=2023-04-04, person=MyTest.Person(name=test3, age=60)}
{idle=2023-04-04, person=MyTest.Person(name=test4, age=50)}
{idle=2023-04-04, person=MyTest.Person(name=test5, age=55)}
=============================================== 开始排序, idele升序, idle相同的age升序
{idle=2022-03-03, person=MyTest.Person(name=test1, age=30)}
{idle=2023-04-04, person=MyTest.Person(name=test4, age=50)}
{idle=2023-04-04, person=MyTest.Person(name=test5, age=55)}
{idle=2023-04-04, person=MyTest.Person(name=test3, age=60)}
{idle=2024-04-04, person=MyTest.Person(name=test2, age=50)}
现在可以看到,结果是我们想要的了