[英]How can I sort a list of maps by value of some specific key using Java 8?
如何使用 Java 8 對Map<String, String>
List
進行排序? 該映射包含一個名為last_name
的鍵,與之關聯的值可能為null
。 我不知道該怎么做,因為以下會導致編譯器錯誤:
List<Map<String, String>> peopleList = ...
peopleList.sort(Comparator.comparing(Map::get, Comparator.nullsLast(Comparator.naturalOrder())));
使用匿名類是唯一的方法嗎?
請注意,我並不是要對列表中的每個地圖進行排序。 我想根據每個地圖中的鍵對列表本身進行排序。
看起來您可以像這樣重寫代碼
peopleList.sort(Comparator.comparing(
m -> m.get("yourKey"),
Comparator.nullsLast(Comparator.naturalOrder()))
)
這應該符合您的要求。
peopleList.sort((o1, o2) -> o1.get("last_name").compareTo(o2.get("last_name")));
如果您想處理空指針,請嘗試這種“老式”解決方案:
peopleList.sort((o1, o2) ->
{
String v1 = o1.get("last_name");
String v2 = o2.get("last_name");
return (v1 == v2) ? 0 : (v1 == null ? 1 : (v2 == null ? -1 : v1.compareTo(v2))) ;
});
如果您想要第一個或最后一個null
值,請切換1
和-1
。
為了徹底起見,我添加了有用的測試用例生成器:
Random random = new Random();
random.setSeed(System.currentTimeMillis());
IntStream.range(0, random.nextInt(20)).forEach(i -> {
Map<String, String> map1 = new HashMap<String, String>();
String name = new BigInteger(130, new SecureRandom()).toString(6);
if (random.nextBoolean())
name = null;
map1.put("last_name", name);
peopleList.add(map1);
});
由於您的peopleList
可能包含一個null
並且Map::key
可能有一個 null 值,您可能需要nullsLast
兩次:
peopleList.sort(Comparator.nullsLast(Comparator.comparing(m -> m.get("last_name"),
Comparator.nullsLast(Comparator.naturalOrder()))));
您可以覆蓋集合的 de compare 方法。 這是一個例子: https : //www.mkyong.com/java8/java-8-lambda-comparator-example/
您將不得不比較對象的 last_name,並且不要忘記正確處理空值。
Steps to sort a Map in Java 8.
1]Convert a Map into a Stream
2]Sort it
3]Collect and return a new LinkedHashMap (keep the order)
Map result = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
嘗試這個:
按鍵:
Map<String, String> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
按價值觀:
Map<String, String> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.