我上了 3 节课。
- Angestellte(仅包含一些内容,例如名称等)
- 部门(仅包含字符串)
- 和 ttest(显然是为了测试)
我想将所有“Angestellte” worker 放入他们的部门。所以基本上输出应该是:
Personalabteilung: 4
Buchhaltung: 3
Fertigung: 3
我正在尝试将 map 作为包含部门和长度的 map 但最终我想要带有 String 和 Long 的 Map。
我还认为我的 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()));
关于java - 流映射中的 java 8 对象和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35013837/