I would like to find the biggest number in HashSet and HashMap. Say I have the number [22,6763,32,42,33] in my HashSet and I want to find the largest number in my current Ha
Note : If you want to find the biggest value from Map try maxEntry.get().getValue() instead of maxEntry.get().getKey()
1. Using Stream
public > V maxUsingStreamAndLambda(Map map) {
Optional> maxEntry = map.entrySet()
.stream()
.max((Entry e1, Entry e2) -> e1.getValue()
.compareTo(e2.getValue())
);
return maxEntry.get().getKey();
}
2. Using Collections.max() with a Lambda Expression
public > V maxUsingCollectionsMaxAndLambda(Map map) {
Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.getKey();
}
3. Using Stream with Method Reference
public > V maxUsingStreamAndMethodReference(Map map) {
Optional> maxEntry = map.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
return maxEntry.get()
.getKey();
}
4. Using Collections.max()
public > V maxUsingCollectionsMax(Map map) {
Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() {
public int compare(Entry e1, Entry e2) {
return e1.getValue()
.compareTo(e2.getValue());
}
});
return maxEntry.getKey();
}
5. Using Simple Iteration
public > V maxUsingIteration(Map map) {
Map.Entry maxEntry = null;
for (Map.Entry entry : map.entrySet()) {
if (maxEntry == null || entry.getValue()
.compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
return maxEntry.getKey();
}