【问题标题】:Java get value of stream used to mapped to another streamJava获取用于映射到另一个流的流的值
【发布时间】:2016-01-25 12:47:07
【问题描述】:

我正在使用以下代码创建 HashMap 条目并搜索存储的最大 。以下剪辑作品::

//key                                                  value
LongStream.rangeClosed( 2 , 1_000_000 ).mapToInt( i -> hm.createAndGet( i) ).max().getAsInt();

如何更改它以返回与最大值关联的 key?换句话说,如何使用流来编写这个循环?

//creates entries and searches for the maximum value stored in hm, and returns the key assosiated with the highest value
int maxValue = -1;
long maxKey = -1;
for(long currentKey = maxNum; currentKey > 0; currentKey --)
{
    int currentValue = hm.createAndGet( currentKey );
    if( maxValue < currentValue )
    {
        maxKey = currentKey ;
        maxStart = currStart;
    }
}
return maxKey;

【问题讨论】:

    标签: java functional-programming hashmap java-stream


    【解决方案1】:

    你可以使用max(Comparator):

    long maxKey = LongStream.rangeClosed( 2 , 1_000_000 )
                            .boxed()
                            .max(Comparator.comparingInt( i -> hm.createAndGet( i ) ) )
                            .get();
    

    但是,不能保证createAndGet 对于每个提供的键只会被调用一次(实际上,对于大多数键,它会被调用两次)。

    另一种解决方案是引入这样的对流:

    long maxKey = LongStream.rangeClosed(2, 1_000_000)
                        .mapToObj(i -> new AbstractMap.SimpleEntry<>(i, hm.createAndGet( i )))
                        .max(Map.Entry.comparingByValue())
                        .get().getKey();
    

    一般而言,Stream API 不应用于在大多数操作中产生副作用(peekforEachforEachOrdered 除外)。例如,在您的代码中,mapToInt 方法是使用有状态 lambda 调用的,而文档 explicitly says 则表明传递的函数必须是无状态的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      相关资源
      最近更新 更多