Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the maximum value using stream for Map

I have a class called Test. This class has a method called getNumber which returns an int value.

public class Test{
     .
     .
     .
     .
     public int getNumber(){
          return number;
     }
}

Also I have a HashMap which the key is a Long and the value is a Test object.

Map<Long, Test> map = new HashMap<Long, Test>(); 

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()));

However my question is How can I return the key of the maximum amount? Can I do it with one round using stream?

like image 239
Moe Mahdiani Avatar asked Oct 04 '17 07:10

Moe Mahdiani


2 Answers

If I understood you correctly:

Entry<Long, Test> entry = map.entrySet()
            .stream()
            .max(Map.Entry.comparingByValue(Comparator.comparingInt(Test::getNumber)))
            .get();
like image 96
Eugene Avatar answered Nov 15 '22 08:11

Eugene


If you want to find the key-value pair corresponding to the maximum 'number' value in the Test instances, you can use Collections.max() combined with a comparator that compares the entries with this criteria.

import static java.util.Comparator.comparingInt;

...

Map.Entry<Long, Test> maxEntry = 
    Collections.max(map.entrySet(), comparingInt(e -> e.getValue().getNumber()))

If you want to use the stream way, then remove the mapping (because you lost the key associated with the value), and provide the same comparator:

map.entrySet()
   .stream()
   .max(comparingInt(e -> e.getValue().getNumber()))
   .ifPresent(System.out::println);

Note that there is a small difference in both snippets, as the first one will throw a NoSuchElementException if the provided map is empty.

like image 42
Alexis C. Avatar answered Nov 15 '22 08:11

Alexis C.