-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
  • 2,847
  • 7
  • 25
  • 34
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
  • 8,893
  • 33
  • 34
  • 46
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,308
  • 7
  • 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
  • 3,934
  • 4
  • 21
  • 43