I am given HashMap<K, V>
.
How to get list of all keys from it, where corresponding value is assignable from class I?
Asked
Active
Viewed 664 times
-8

Stefan Zobel
- 3,182
- 7
- 28
- 38

J. Doe
- 39
- 1
- 5
-
1Possible duplicate of [How to return a list of keys from a Hash Map?](http://stackoverflow.com/questions/6589744/how-to-return-a-list-of-keys-from-a-hash-map) – Todd Sewell Feb 14 '17 at 21:43
-
3Seriously, you need to at least try something. HashMap is well documented, and you should know about loops. – JB Nizet Feb 14 '17 at 21:44
-
I know, but aren't there more efficient ways to do this instead of iterating through HashMap? – J. Doe Feb 14 '17 at 21:46
-
Sure there are more concise ways, if you use Java-8 streams – Thomas Fritsch Feb 14 '17 at 21:49
-
Yes, I can use Java-8 streams. Can you tell me how to do it this way? – J. Doe Feb 14 '17 at 21:53
-
3There is a big difference between "efficient" and "concise". Using a stream won't prevent iterating through the entries of the map. – JB Nizet Feb 14 '17 at 21:57
-
@JBNizet ok, you are right – Thomas Fritsch Feb 14 '17 at 22:15
3 Answers
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