【问题标题】:Value Function for java.util.stream.Collectors.toMap() returning constant value [duplicate]java.util.stream.Collectors.toMap() 的值函数返回常量值
【发布时间】:2019-05-18 15:49:22
【问题描述】:

我正在尝试创建一个 Map,其中键运行值从 1 到 N,并且每个 kesys 的值都是一些常数-

 private Map<Integer, Integer> getInitialDistMap(int N) {
    Function<Integer, Integer> constant = x -> Integer.MAX_VALUE;
    return IntStream.rangeClosed(1, N).collect(Collectors.toMap(Function.identity(), constant));
}

这个结构给了我错误。

【问题讨论】:

    标签: java function stream java-stream


    【解决方案1】:

    IntStream.rangeClosed() 返回 IntStream 而不是 Stream&lt;Integer&gt;IntStreamints 的原始流。要将IntStream 转换为Stream&lt;Integer&gt;,您需要在流中调用IntStream.boxed()

    private Map<Integer, Integer> getInitialDistMap(int N) {
        Function<Integer, Integer> constant = x -> Integer.MAX_VALUE;
        return IntStream.rangeClosed(1, N).boxed()
                .collect(Collectors.toMap(Function.identity(), constant));
    }
    

    【讨论】:

      【解决方案2】:

      静态 IntStream rangeClosed(int startInclusive,int endInclusive)

      rangeClosed 将返回IntStreamIntStream 上唯一可用的收集方法是

      <R> R collect(Supplier<R> supplier,ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)
      

      所以使用boxed(),它返回Stream&lt;Integers&gt;整数流,然后收集到Map

      Stream<Integer> boxed()
      

      返回一个由该流的元素组成的流,每个元素都装箱为一个整数。

      解决方案

      IntStream.rangeClosed(1, N).boxed().collect(Collectors.toMap(Function.identity(), constant));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-06
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 2016-03-03
        • 2012-01-18
        • 1970-01-01
        相关资源
        最近更新 更多