I have a hashmap and want to return the smallest key which value is 0
hashmap:
10 1
2 1
3 1
4 0
8 0
it will return 4
while( map.containsValue(0))
{
int minValue=(Collections.min(map.keySet()));
if( map.containsKey(minValue))
{
System.out.println(minValue);
}
break;
}
CodePudding user response:
In a non-empty Map you can find the Map.Entry with minimum key having value 0 by:
Map.Entry<Integer,Integer> entry = map.entrySet().stream()
.filter(e -> e.getValue() == 0)
.min(Comparator.comparingInt(Map.Entry::getKey))
.get();
System.out.printf("Key %d with value %d%n", entry.getKey(), entry.getValue());
CodePudding user response:
If you use a TreeMap
where the entries are sorted by keys, you can return the first entry that has a value of 0
. Then simply get the key
for that entry.
SortedMap<Integer, Integer> map =
new TreeMap<>(Map.of(2, 1, 3, 1, 4, 0, 8, 0));
Integer key =
map.entrySet().stream().filter(e -> e.getValue() == 0)
.findFirst().map(Entry::getKey).orElse(null);
System.out.println(key);
prints
4
Note: If all that is required is a single lookup, then simply iterating over a regular HashMap
would be more efficient. The advantage of a TreeMap
is that it lends itself to get the key for subsequent retrievals without repeated iterations.