Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to return key of a map after computation on its values by Java 8

If the size of map is 1 then its key should be returned. If it's size is greater than 1 then iterate over the values in map and the key of that one should be returned which has a max value for a certain property. Below is my code snippet. I want to achieve the same with Java 8 streams api.

public  MessageType getOrgReversalTargetMti(Map<MessageType, List<TVO>> map) {
    MessageType targetMessageType = null;
    if (1 == map.size()) {
        targetMessageType = map.keySet().iterator().next();
    }
    else {
        long maxNumber = 0;
        for (final MessageType messageType : map.keySet()) {
            List<TVO> list = map.get(messageType);
            long trace = list.get(0).getTrace();
            if (trace > maxNumber) {
                maxNumber = trace;
                targetMessageType = messageType;
            }
        }
    }
    return targetMessageType;
}
like image 928
Tishy Tash Avatar asked Jan 02 '20 13:01

Tishy Tash


People also ask

Which method returns the list of maps as a result in Java?

so they are defined as follows: map. values() will return a Collection of the map's values.

What will map return if key not found?

If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

How do I change the value of a key in a HashMap?

hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.


1 Answers

You can use a Stream with max() terminal operation:

public  MessageType getOrgReversalTargetMti(Map<MessageType, List<TVO>> map) {
    return map.entrySet()
              .stream()
              .max(Comparator.comparing(e -> e.getValue().get(0).getTrace()))
              .map(Map.Entry::getKey())
              .orElse(null);
}
like image 126
Eran Avatar answered Oct 22 '22 05:10

Eran