![](/img/trans.png)
[英]Transform Map<String, Object> to Object using Java streams
[英]Streams java 8 Object and String in Map
我上了3節課。
我想將所有“ Angestellte”工人納入他們的部門。 所以基本上輸出應該是:
Personalabteilung: 4
Buchhaltung: 3
Fertigung: 3
我試圖將Map設置為Department和Long的Map,但最終我希望Map使用String和Long。
我也認為我的Collectors.counting()
不能像我所說的那樣工作。
在映射完字符串流之后,我真的不知道該如何解決它。 那就是為什么我放三個? 在代碼中。
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class ttest {
public static void main(String[] args){
Department d1 = new Department("Personalabteilung");
Department d2 = new Department("Buchhaltung");
Department d3 = new Department("Fertigung");
List<Angestellte> AlleAng = Arrays.asList(
new Angestellte("Sandra","Bullock",d3,3450, "Female"),
new Angestellte("Yutta","Knie",d1,2800, "Female"),
new Angestellte("Ludwig","Herr",d3,3850, "Male"),
new Angestellte("Peter","Pan",d2,1850, "Male"),
new Angestellte("Nicky","Smith",d3,2100, "Female"),
new Angestellte("Herbert","Rotwein",d2,2450, "Male"),
new Angestellte("Sandra","Siech",d1,1100, "Female"),
new Angestellte("Florian","Schwarzpeter",d2,2800, "Male"),
new Angestellte("Herrietta","Glas",d1,2100, "Female"),
new Angestellte("Brock","Builder",d1,6000, "Male"));
Map<Department, Long> DepAnz = AlleAng.stream()
.map(a -> a.getDep())
.collect(Collectors.toMap(a.getDep???, Collectors.counting()));
}
}
如果您想按部門分組並且您的getter稱為getDep()
可以執行
Map<Department, Long> DepAnz = AlleAng.stream()
.collect(Collectors.groupingBy(a -> a.getDep(), Collectors.counting()));
您需要使用分組依據:
Map<Department, Long> DepAnz =
AlleAng.stream()
.collect(Collectors.groupingBy(Angestellte::getDep, Collectors.counting()));
groupingBy(classifier, downstream)
收集器是將Stream元素收集到Map
中的收集器, groupingBy(classifier, downstream)
器返回了鍵,這些值是將下游收集器應用於具有相同鍵的所有Stream元素的結果。 在這種情況下,我們想要計數值,因此我們將Collectors.counting()
用作下游收集器。
如果您想按部門名稱分組,則可以通過將getter .getName()
為.getName()
來檢索名稱:
Map<String, Long> DepAnz =
AlleAng.stream()
.collect(Collectors.groupingBy(a -> a.getDep().getName(), Collectors.counting()));
這將返回所有部門名稱的計數。
Map<String, Long> map = AlleAng.stream().collect(Collectors.toMap(a -> a.getDept().getName(), a -> 1L, (Long acc, Long newValue) -> acc + newValue));
這是lambda的冗長用法,以實現您所需要的。 使用toMap Collector可以根據實際的Angestellte引用映射特定的鍵和值。 當然,石斑魚功能最適合,但這可以作為按某些標准對地圖進行分組的通用示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.