Is there a convenient way for such conversion other than a for loop such as
List<Map.Entry<String, Integer>> entryList = new List<>(//initialization);
List<String>> keyList = new List<>(entryList.size());
for (Map.Entry<String, Integer> e : entryList) {
keyList.add(e.getKey());
}
I would like the order to be preserved.
We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
If you want to use an ArrayList as a map key, you will need to override equals() and hashcode() in order to make two arraylists with the same content in the same order return true on a call to equals() and return the same hashcode on a call to hashcode() .
util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Use java 8 streams to convert this:
List<Map.Entry<String, ?>> entryList = new List<>(//initialization);
List<String> stringList = entryList.stream().map(Entry::getKey).collect(Collectors.toList());
This makes a stream of the entries, then uses the map method to convert them to strings, then collects it to a list using Collectors.toList()
.
Alternatively, this method can be changed in a helper function if you need it more times like this:
public static <K> List<K> getKeys(List<Map.Entry<K,?>> entryList) {
return entryList.stream().map(Entry::getKey).collect(Collectors.toList());
}
public static <V> List<V> getValues(List<Map.Entry<?,V>> entryList) {
return entryList.stream().map(Entry::getValue).collect(Collectors.toList());
}
While the above code works, you can also get a List<K>
from a map by doing new ArrayList<>(map.keySet())
, with this having the advantage than you don't need to convert the entryset
to a list, before converted to a stream, and then back a list again.
If you do not really need to make a copy of the list you can implement a wrapper arround the list like this, with the adicional bonus that changes made to the entryList are automatically reflected in the stringList. Bear in mind that this simple wrapper is read only.
List<Map.Entry<String, ?>> entryList = new List<>(//initialization);
List<String> stringList = new AbstractList<String>() {
List<Map.Entry<String, Integer>> internal = entryList;
public String get(int index) {
return internal.get(index).getKey();
}
public int size() {
return internal.size();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With