Reputation: 56931
I want to create a new map from the keyset()
of an existing HashMap
that maps a key to its index in the map.
Here's my attempt, which works:
Map<String, Integer> keysToIndex = new HashMap<>();
Integer index = 0;
for (String obj: hashMap.keySet()) {
keysToIndex.put(obj, index);
index += 1;
}
Does Java 8 provide features to create a map of each key's index, or is there a more idiomatic way to write this snippet?
Upvotes: 3
Views: 586
Reputation: 425198
Sets aren't ordered, so the "index" of an element in a Set is arbitrary (albeit unique). The "index" is simply the current size of the map, so you can use the result map's state to provide the index:
Map<String, Integer> keysToIndex = new HashMap<>();
hashMap.keySet().forEach(k -> keysToIndex.put(k, keysToIndex.size()));
This is more or less what your code is doing, but more compact since no extra variables or instructions are needed.
Incidentally, you can drop one more method call by using forEach()
directly on the source map (and ignoring the value argument of the BiConsumer
):
Map<String, Integer> keysToIndex = new HashMap<>();
hashMap.forEach((k, v) -> keysToIndex.put(k, keysToIndex.size()));
Upvotes: 3