Moe*_*ani 5 java-8 java-stream
我有一个名为 Test 的课程。这个类有一个名为 getNumber 的方法,它返回一个 int 值。
public class Test{
.
.
.
.
public int getNumber(){
return number;
}
}
Run Code Online (Sandbox Code Playgroud)
我还有一个 HashMap ,它的键是 Long ,值是一个 Test 对象。
Map<Long, Test> map = new HashMap<Long, Test>();
Run Code Online (Sandbox Code Playgroud)
I want to print the key and also getNumber which has a maximum getNumber using a Stream Line code.
I can print the maximum Number via below lines
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()));
Run Code Online (Sandbox Code Playgroud)
However my question is How can I return the key of the maximum amount? Can I do it with one round using stream?
如果我理解正确的话:
Entry<Long, Test> entry = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue(Comparator.comparingInt(Test::getNumber)))
.get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4445 次 |
| 最近记录: |