【问题标题】:How to create a map with Java stream API using a value outside the stream?如何使用流外的值创建带有 Java 流 API 的地图?
【发布时间】:2016-07-21 05:50:17
【问题描述】:

我想初始化一个 Map<String, BigDecimal> 并希望始终从流外部放置相同的 BigDecimal 值。

BigDecimal samePrice;
Set<String> set;

set.stream().collect(Collectors.toMap(Function.identity(), samePrice));

然而 Java 抱怨如下:

类型 Collectors 中的方法 toMap(Function, Function) 不适用于参数 (函数,BigDecimal)

为什么我不能从外部使用 BigDecimal?如果我写:

set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));

它会起作用,但这当然不是我想要的。

【问题讨论】:

    标签: java java-8 java-stream collectors


    【解决方案1】:

    toMap(keyMapper, valueMapper) 的第二个参数(和第一个参数一样)是一个函数,它接受流元素并返回映射的值。

    在这种情况下,你想忽略它,这样你就可以拥有:

    set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
    

    请注意,出于同样的原因,您的第二次尝试不会奏效。

    【讨论】:

      【解决方案2】:

      Collectors#toMap 需要两个 Functions

      set.stream().collect(Collectors.toMap(Function.identity(), x -> samePrice));
      

      您可以在JavaDoc 中找到几乎相同的示例

       Map<Student, Double> studentToGPA
           students.stream().collect(toMap(Functions.identity(),
                                           student -> computeGPA(student)));
      

      【讨论】:

        【解决方案3】:

        正如在其他答案中已经说过的,您需要指定一个函数,将每个元素映射到固定值,例如element -&gt; samePrice

        另外,如果你想专门填写一个ConcurrentHashMap,有一个简洁的功能根本不需要流操作:

        ConcurrentHashMap<String,BigDecimal> map = new ConcurrentHashMap<>();
        map.keySet(samePrice).addAll(set);
        

        很遗憾,没有针对任意Maps的这种操作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-12
          • 2011-02-23
          相关资源
          最近更新 更多