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;
}
so they are defined as follows: map. values() will return a Collection of the map's values.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With