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 HashSet..how would i do this? and Same thing for the HashMap as well. I hope you can help me with it. Thank you.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can use
Collections.max(Collection)
to find the maximum element out of any collection. Similarly, for aHashMap
, you can use the same method on itskeySet()
orvalues()
, depending upon whether you want maximum key, or maximum value.Also, if you want as such, you can use a
TreeSet
andTreeMap
instead, that stores the elements in sorted key order.Note : If you want to find the biggest value from Map try maxEntry.get().getValue() instead of maxEntry.get().getKey()
1. Using Stream
2. Using Collections.max() with a Lambda Expression
3. Using Stream with Method Reference
4. Using Collections.max()
5. Using Simple Iteration
Here is a simple method which does what you are asking:
In case of TreeMap, if you know the key/values are inserted randomly, the tree will be more or less balanced. Trees become unbalanced, if data is inserted in already sorted order, the capability to quickly find (or insert or delete) a given element is lost. In case of unbalanced tree, it will take time proportional to n, O(n) else O(1).
If you are forced to use a
HashSet
/HashMap
, then you have to scan the wholeHashSet
/HashMap
in order to find the maximum. Library functions likeCollections.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
).try