在 Java 流 API 中按函数收集参数
Collect by function with parameter in Java Stream API
根据教程 here,我发现我可以按属性对对象进行分组:
Map<Person.Sex, List<Person>> byGender =
roster
.stream()
.collect(
Collectors.groupingBy(Person::getGender));
如果我需要按采用参数的方法进行分组,例如 steve.get("height")
而不是 steve.getHeight()
,该怎么办?我怀疑这可以用 lambda 来完成,但我找不到正确的语法。我现在得到的是:
people.stream().collect(Collectcors.groupingBy(p -> p.get("height")));
根据 lambda 函数的结果进行分组的正确语法是什么?
想通了:
people.stream().collect(Collectors.groupingBy(p -> p.get("height"), Collectors.toSet()));
根据教程 here,我发现我可以按属性对对象进行分组:
Map<Person.Sex, List<Person>> byGender =
roster
.stream()
.collect(
Collectors.groupingBy(Person::getGender));
如果我需要按采用参数的方法进行分组,例如 steve.get("height")
而不是 steve.getHeight()
,该怎么办?我怀疑这可以用 lambda 来完成,但我找不到正确的语法。我现在得到的是:
people.stream().collect(Collectcors.groupingBy(p -> p.get("height")));
根据 lambda 函数的结果进行分组的正确语法是什么?
想通了:
people.stream().collect(Collectors.groupingBy(p -> p.get("height"), Collectors.toSet()));