如何使用Java 8对地图列表进行排序? [英] How can I sort a list of maps using Java 8?
本文介绍了如何使用Java 8对地图列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Java 8对 Map< String,String>
的列表
进行排序?该映射包含一个名为 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.
推荐答案
看起来你可以像<一样重写你的代码/ p>
It looks like you can rewrite your code like
peopleList.sort(Comparator.comparing(
m -> m.get("yourKey"),
Comparator.nullsLast(Comparator.naturalOrder()))
)
这篇关于如何使用Java 8对地图列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文