1

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;       
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • 1
    https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap – SedJ601 Aug 20 '22 at 20:24
  • Set `minValue = Integer.MAX_VALUE`. Set `key = someDefaultValue or null`.Iterate through the values. If a value is less than minValue, minValue = that value and key equals that key. – SedJ601 Aug 20 '22 at 20:28
  • `minValue` was obtained from the key set, so `containsKey` will always return true. The while loop never loops, so should just be an if-statement – Michael Aug 20 '22 at 20:40
  • You should instead use a TreeMap. TreeMaps are ordered by keys, so you just iterate over the map until the first entry with value zero is found. – Gabriel Belingueres Aug 20 '22 at 20:49

2 Answers2

3

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());
Mihe
  • 2,270
  • 2
  • 4
  • 14
2

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.

WJS
  • 36,363
  • 4
  • 24
  • 39