[英]Converting List<Map.Entry<Key, Value>> to List<Key> in Java
Is there a convenient way for such conversion other than a for loop such as 除了for循环之外,还有一种方便的方法进行这种转换
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 streams to convert this: 使用java 8流来转换它:
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()
. 这将创建条目流 ,然后使用map方法将它们转换为字符串,然后使用
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. 虽然上面的代码可以工作,你也可以通过执行
new ArrayList<>(map.keySet())
从地图中获取List<K>
,这样做的好处就是你不需要将entryset
转换为list ,在转换为流之前,然后再次返回列表。
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. 如果你真的不需要复制列表,你可以像这样在列表周围实现一个包装器,并且对entryList的更改会自动反映在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();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.