Collectors.groupingBy 和地图
Collectors.groupingBy and map
我正在努力 groupBy
在用 Doubles 计算后命名所有的人。
persons.stream()
.map(p -> (p.getHeight() * p.getWeight()))
.collect(Collectors.groupingBy(Person::getName)));
但 Stream<Double>
不适用于这些参数。
如何处理整数/双精度数,然后再处理 groupBy 字符串?
它不起作用,因为您的 map
正在将它从 Person
映射到 Integer
或 Double
,(取决于 height/weight 的测量方式)。 map
调用完成后,您实际上拥有了一个数字流,因此您无法将它们收集为 Person
个对象。
persons.stream() // Stream of Person objects
.map(p -> (p.getHeight() * p.getWeight())) // Stream of numbers.
Stream.map() 的 JavaDoc 证实了这一点:
Returns a stream consisting of the results of applying the given function to the elements of this stream.enter link description here
也许如果我们更多地了解您尝试使用流做什么,我们可以就如何解决问题给您更直接的答案。
一种可能的解决方案如下:
persons.stream().collect(Collectors.groupingBy(
Person::getName,
HashMap::new,
Collectors.mapping(
p -> p.getHeight() * p.getWeight()
Collectors.toList())));
或者,如果您不希望出现重复名称,则可以使用更简单的方法
persons.stream().collect(Collectors.toMap(
Person::getName,
p -> p.getHeight() * p.getWeight()));
我正在努力 groupBy
在用 Doubles 计算后命名所有的人。
persons.stream()
.map(p -> (p.getHeight() * p.getWeight()))
.collect(Collectors.groupingBy(Person::getName)));
但 Stream<Double>
不适用于这些参数。
如何处理整数/双精度数,然后再处理 groupBy 字符串?
它不起作用,因为您的 map
正在将它从 Person
映射到 Integer
或 Double
,(取决于 height/weight 的测量方式)。 map
调用完成后,您实际上拥有了一个数字流,因此您无法将它们收集为 Person
个对象。
persons.stream() // Stream of Person objects
.map(p -> (p.getHeight() * p.getWeight())) // Stream of numbers.
Stream.map() 的 JavaDoc 证实了这一点:
Returns a stream consisting of the results of applying the given function to the elements of this stream.enter link description here
也许如果我们更多地了解您尝试使用流做什么,我们可以就如何解决问题给您更直接的答案。
一种可能的解决方案如下:
persons.stream().collect(Collectors.groupingBy(
Person::getName,
HashMap::new,
Collectors.mapping(
p -> p.getHeight() * p.getWeight()
Collectors.toList())));
或者,如果您不希望出现重复名称,则可以使用更简单的方法
persons.stream().collect(Collectors.toMap(
Person::getName,
p -> p.getHeight() * p.getWeight()));