我有一个地图列表,下面是
[{address=North Wilshire, name=Joe, age=16},
{address=South Wilshire, name=Zealot, age=12},
{address=South Wilshire, name=Astrid, age=23},
{address=North Wilshire, name=Aaron, age=23}],
{address=South Wilshire, name=Aaron, age=21}]
,我想将它与另一个映射列表排序,如下所示
[{column=name, direction=ASC}, {column=age, direction=ASC}]
我希望能够先按名字排序,然后按年龄排序(如果两个名字是相同的,它将按值排序),所以最终将看起来像下面这样:
[{address=South Wilshire, name=Aaron, age=21}, {address=North Wilshire, name=Aaron, age=23}, {address=South Wilshire, name=Astrid, age=23}, {address=North Wilshire, name=Joe, age=16}, {address=South Wilshire, name=Zealot, age=12}]
带有列的映射将是动态的,因此可能需要对所有字段进行排序,有时可能需要对一个字段进行排序
我尝试使用集合。使用comparator . compare进行排序以获得结果,但无法使其适用于多列:
Collections.sort(listOfMapsToSort, Comparator.comparing(o -> o.get(otherListOfMap.get(0).get("column"))));
我试图循环otherListOfMap,但无法得到它的权利
有一种方法。
List<Map<String, String>> listOfMaps =new ArrayList<>(List.of(
Map.of("address", "North Wilshire", "name", "Joe", "age", "16"),
Map.of("address", "South Wilshire", "name", "Zealot", "age",
"12"),
Map.of("address", "South Wilshire", "name", "Astrid", "age",
"23"),
Map.of("address", "North Wilshire", "name", "Aaron", "age",
"23"),
Map.of("address", "South Wilshire", "name", "Aaron", "age",
"21")));
// the other map that specifies the columns
List<Map<String, String>> sortCriteria = List
.of(Map.of("Column", "name"), Map.of("Column", "age"));
// the comparator for that specification
Comparator<Map<String, String>> comp = Comparator
.comparing((Map<String, String> map) -> map
.get(sortCriteria.get(0).get("Column")))
.thenComparing((Map<String, String> map) -> map
.get(sortCriteria.get(1).get("Column")));
listOfMaps.sort(comp); // change comp to sort differently.
listOfMaps.forEach(System.out::println);
打印
{name=Aaron, address=South Wilshire, age=21}
{name=Aaron, address=North Wilshire, age=23}
{name=Astrid, address=South Wilshire, age=23}
{name=Joe, address=North Wilshire, age=16}
{name=Zealot, address=South Wilshire, age=12}
然而,一个更好的方法是创建一个类或记录来保存这些值,并使用getter来获取这些值。您还可以在类中混合类型,而在映射中则不能。所以age可以是int