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

Tishy Tash :

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;
}
Eran :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414808&siteId=1