Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java8流在映射中查找最小密钥_Java_Filtering_Java Stream - Fatal编程技术网

使用Java8流在映射中查找最小密钥

使用Java8流在映射中查找最小密钥,java,filtering,java-stream,Java,Filtering,Java Stream,我试图在地图中找到一个最小的键值。我在映射的值部分插入一个AtomicLong,初始化为系统时间,如下所示: map.putIfAbsent(instr,new AtomicLong(System.currentTimeMillis())); 然后在稍后阶段,我想知道最小值,下面是代码片段: map.entrySet() .stream() .filter(key -> key.getKey().getSymbol() == this.symbol) .min(Map

我试图在地图中找到一个最小的键值。我在映射的值部分插入一个
AtomicLong
,初始化为系统时间,如下所示:

map.putIfAbsent(instr,new AtomicLong(System.currentTimeMillis())); 
然后在稍后阶段,我想知道最小值,下面是代码片段:

map.entrySet()
   .stream()
   .filter(key -> key.getKey().getSymbol() == this.symbol)
   .min(Map.Entry.comparingByValue())
   .get()
   .getKey()
我得到以下错误:

The method min(Comparator<? super Map.Entry<Instrument,AtomicLong>>) in the type
Stream<Map.Entry<Instrument,AtomicLong>> is not applicable for the arguments 
(Comparator<Map.Entry<Object,Comparable<? super Comparable<? super V>>>>)
方法min(Comparator与自身相当,因为它实现了
comparable

不可比的,因为它没有实现
可比,这需要
可比的

您可以尝试以下方法:

.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicL‌​ong::get)))
与自身可比,因为它实现了
compariable

不可比的,因为它没有实现
可比,这需要
可比的

您可以尝试以下方法:

.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicL‌​ong::get)))

是否确实需要
Map.Entry.comparingByValue()

您可以“实现”您(几乎:)自己的
比较器

.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )

是否确实需要
Map.Entry.comparingByValue()

您可以“实现”您(几乎:)自己的
比较器

.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )


就像错误所说:
Comparator就像错误所说:
Comparator“出于线程安全考虑,我将
Map
中的
V
部分从
Long
更改为
AtomicLong
。”为什么?难道
Long
不像
AtomicLong
那样不可更改吗?@TimothyTruckle
AtomicLong
不是不可更改的,所以
Long
更不可更改。@Michael还有一个不更改的理由……”出于线程安全考虑,我将
Map
中的
V
部分从
Long
更改为
AtomicLong
。“为什么?
Long
不是像
AtomicLong
那样不可变吗?@TimothyTruckle
AtomicLong
不是不可变的,所以
Long
更不可变。@Michael还有一个不改变的理由……可能更简单:
.min(Comparator.comparingLong(e->e.getValue().get())
甚至更复杂,可能:
.min(Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
所有这些解决方案的问题在于,比较不是原子的。如果没有额外的锁,它就不可能是原子的。非常感谢@kotslon和您的建议,非常感谢!非常感谢@Enwired的建议,非常感谢!更简单的可能是:
.min(Comparator.comparingLong(e->e.getValue()).get())
可能更复杂:
.min(Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
所有这些解决方案的问题在于,比较不是原子性的。如果没有额外的锁,它就不可能是原子性的。非常感谢@kotslon,感谢你的建议,非常感谢!非常感谢@Enwired,感谢你的建议,非常感谢!你可以使用。@shmosel正确,但也许我们都应该解释一下这是关于我们所指的签名。你可以使用。@shmosel是正确的,但也许我们都应该明确我们所指的签名。