如何使用Java 8按某些特定键的值对地图列表进行排序? [英] How can I sort a list of maps by value of some specific key using Java 8?
本文介绍了如何使用Java 8按某些特定键的值对地图列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Java 8对Map<String, String>
的List
进行排序?该映射包含一个名为last_name
的键,并且与之关联的值可能是null
.我不确定该怎么做,因为以下情况会导致编译器错误:
How can I sort a List
of Map<String, String>
using Java 8? The map contains a key called last_name
, and the value associated with it may be null
. I'm not sure how to do it because the following results in a compiler error:
List<Map<String, String>> peopleList = ...
peopleList.sort(Comparator.comparing(Map::get, Comparator.nullsLast(Comparator.naturalOrder())));
使用匿名类是唯一的方法吗?
Is using an anonymous class the only way to do it?
请注意,我不尝试对列表中的每个地图进行排序.我想根据每个地图中的键对列表本身进行排序.
Note that I am not trying to sort each map in the list. I want to sort the list itself based on a key in each map.
推荐答案
看起来您可以像这样重写代码
It looks like you can rewrite your code like
peopleList.sort(Comparator.comparing(
m -> m.get("yourKey"),
Comparator.nullsLast(Comparator.naturalOrder()))
)
这篇关于如何使用Java 8按某些特定键的值对地图列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文