Reputation: 357
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;
}
Upvotes: 5
Views: 118
Reputation: 393801
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);
}
Upvotes: 8