Convert list <Map.Entry <Key, value >> to display <Key> in Java
Is there a convenient way for such a conversion besides 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.
Use java 8 threads to convert:
List<Map.Entry<String, ?>> entryList = new List<>(//initialization); List<String> stringList = entryList.stream().map(Entry::getKey).collect(Collectors.toList()); This makes stream entries, then uses the map method to convert them to strings, and then collects it into a list using Collectors.toList() .
Alternatively, this method can be changed in a helper function if you need more time, for example:
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 code above works, you can also get List<K> from the map by doing new ArrayList<>(map.keySet()) , having this advantage than you don't need to convert the entryset to a list before converting to stream, and then return the list again.
If you really do not need to make a copy of the list, you can implement a wrapper around a list like this with the adicional bonus that is listed in the entryList, automatically reflected in stringList. Keep in mind that this simple shell 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(); } };