有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java收藏家。分组方式和地图

我正在努力groupBy在用双倍计算后说出所有人的名字

persons.stream()
                .map(p -> (p.getHeight() * p.getWeight()))
                .collect(Collectors.groupingBy(Person::getName)));

但是Stream<Double>不适用于这些论点

如何处理整数/双精度,然后按字符串分组


共 (2) 个答案

  1. # 1 楼答案

    它不起作用,因为你的map正在将它从Person映射到IntegerDouble(取决于身高/体重的测量方式)。一旦map调用完成,实际上就有了一个数字流,因此不能将它们作为Person对象收集

    persons.stream() // Stream of Person objects
      .map(p -> (p.getHeight() * p.getWeight())) // Stream of numbers.
    

    还有流的JavaDoc。map()证实了这一点:

    Returns a stream consisting of the results of applying the given function to the elements of this stream.enter link description here

    也许如果我们知道更多关于你试图用这些流做什么,我们可以给你一个更直接的答案,如何解决这个问题

  2. # 2 楼答案

    一种可能的解决办法如下:

     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()));