![](/img/trans.png)
[英]Java-Stream - How to apply sorting while using Collector groupingBy
[英]Java-Stream - Grouping and Sorting based on aggregate count in Java 11
我有一個Stream
的自定義對象作為方法的參數。 顯然我只能使用 Stream 一次。
我的 object 有一個名為category
的String
屬性。
public class MyType {
private String category;
// other properties, getters, etc.
}
我需要一個分類列表List<String>
。
首先,我需要根據每個類別的出現次數對數據進行排序。 如果出現次數相同,則按字典順序對此類類別進行排序。
基本上,我需要這樣的東西
但我沒有不止一次消費 stream 的奢侈。 所以我不知道如何解決這個問題。
這是一個例子:
輸入:
{
object1 :{category:"category1"},
object2 :{category:"categoryB"},
object3 :{category:"categoryA"},
object4 :{category:"category1"},
object5 :{category:"categoryB"},
object6 :{category:"category1"},
object7 :{category:"categoryA"}
}
Output:
List = {category1, categoryA, categoryB}
您可以為類型為Map<String,Long>
的每個類別生成 Map 的頻率(按類別計數)。
然后在其條目上創建一個 stream 並對它們進行排序(按值,即按計數,和鍵,即字典順序),從每個條目中提取類別並將結果存儲到列表中。
假設您具有以下域類型:
public class MyType {
private String category;
// getters
}
生成分類列表的方法可以這樣實現:
public static List<String> getSortedCategories(Stream<MyType> stream) {
return stream.collect(Collectors.groupingBy(
MyType::getCategory,
Collectors.counting()
))
.entrySet().stream()
.sorted(
Map.Entry.<String, Long>comparingByValue()
.thenComparing(Map.Entry.comparingByKey())
)
.map(Map.Entry::getKey)
.toList();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.