Find the Biggest number in HashSet/HashMap java
Something like this:
Set<Integer> values = new HashSet<Integer>() {{
add(22);
add(6763);
add(32);
add(42);
add(33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values) {
if (value > maxValue) {
maxValue = value;
}
}
And this:
Map<String, Integer> values = new HashMap<String, Integer>() {{
put("0", 22);
put("1", 6763);
put("2", 32);
put("3", 42);
put("4", 33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values.values()) {
if (value > maxValue) {
maxValue = value;
}
}
try
int max = Collections.max(set);
int maxKey = Collections.max(map.keySet());
int maxValue Collections.max(map.values());
If you are forced to use a HashSet
/HashMap
, then you have to scan the whole HashSet
/HashMap
in order to find the maximum. Library functions like Collections.max()
will do like this.
If you want O(1)
retrieval of the maximum, and you are allowed to change the type of collection being used, use a sorted set/map (e.g. TreeSet
/TreeMap
).
You can use Collections.max(Collection)
to find the maximum element out of any collection.
Similarly, for a HashMap
, you can use the same method on its keySet()
or values()
, depending upon whether you want maximum key, or maximum value.
Also, if you want as such, you can use a TreeSet
and TreeMap
instead, that stores the elements in sorted key order.