-8

I am given HashMap<K, V>. How to get list of all keys from it, where corresponding value is assignable from class I?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
J. Doe
  • 39
  • 1
  • 5

3 Answers3

3

Using Java 8 you can do

Map<K, V> map = new HashMap<>();
List<K> list = map.entrySet().stream()
        .filter(e -> e.getValue() instanceof I)
        .map(e -> e.getKey())
        .collect(Collectors.toList());
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
0

where corresponding value is assignable from class I

Do you mean value.getClass().isAssignableFrom(I.class) ? If it's this the case:

Map<K, V> map = ...
List<K> keys = new ArrayList<K>();

for(K key : map.keySet()) {
    V value = map.get(key);

    if(value.getClass().isAssignableFrom(I.class)) {
        keys.add(key);
    }
}

//Now you have a list of keys associated to values that are assignable from I.class
Flood2d
  • 1,338
  • 8
  • 9
0

You can filter the values of the Map using Streams.

Map<K, V> map = new HashMap<>();
List<K> collect = map.entrySet()
                    .stream()
                    .filter(entry -> I.class.isInstance(entry.getValue()))
                    .map(Map.Entry::getKey)
                    .collect(toList());
alayor
  • 4,537
  • 6
  • 27
  • 47