我有一个名为Test的课程。这个类有一个名为getNumber的方法,它返回一个int值。
public class Test{
.
.
.
.
public int getNumber(){
return number;
}
}
我还有一个HashMap,键是Long,值是Test对象。
Map<Long, Test> map = new HashMap<Long, Test>();
我想打印密钥以及使用Stream Line代码获取最大getNumber的getNumber。
我可以通过以下行打印最大数量
final Comparator<Test> comp = (p1, p2) -> Integer.compare(p1.getNumber(), p2.getNumber());
map.entrySet().stream().map(m -> m.getValue())
.max(comp).ifPresent(d -> System.out.println(d.getNumber()));
但我的问题是如何退回最高金额的钥匙?我可以使用流进行一轮吗?
答案 0 :(得分:2)
如果我理解正确的话:
Entry<Long, Test> entry = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue(Comparator.comparingInt(Test::getNumber)))
.get();
答案 1 :(得分:1)
如果要查找与测试实例中的最大“数字”值对应的键值对,可以使用Collections.max()
结合比较条件的比较器。
import static java.util.Comparator.comparingInt;
...
Map.Entry<Long, Test> maxEntry =
Collections.max(map.entrySet(), comparingInt(e -> e.getValue().getNumber()))
如果要使用流方式,则删除映射(因为丢失了与该值关联的密钥),并提供相同的比较器:
map.entrySet()
.stream()
.max(comparingInt(e -> e.getValue().getNumber()))
.ifPresent(System.out::println);
请注意,两个片段之间存在细微差别,因为如果提供的地图为空,第一个片段会抛出NoSuchElementException
。