Jav*_*vaa 643 java collections list map
将a转换Map<key,value>为a 的最佳方法是List<value>什么?只是迭代所有值并将它们插入列表中或者我忽略了什么?
cle*_*tus 1254
List<Value> list = new ArrayList<Value>(map.values());
Run Code Online (Sandbox Code Playgroud)
假设:
Map<Key,Value> map;
Run Code Online (Sandbox Code Playgroud)
coo*_*ird 133
这里的问题是它Map有两个值(一个键和一个值),而一个List只有一个值(一个元素).
因此,可以做的最好的事情是获得一个List键或值.(除非我们使用包装器来保持键/值对).
说我们有一个Map:
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
Run Code Online (Sandbox Code Playgroud)
作为a的键List可以通过ArrayList从方法Set返回的新建来获得Map.keySet:
List<String> list = new ArrayList<String>(m.keySet());
Run Code Online (Sandbox Code Playgroud)
而作为该值List能够获得创建新的ArrayList从Collection由返回的Map.values方法:
List<String> list = new ArrayList<String>(m.values());
Run Code Online (Sandbox Code Playgroud)
获取List密钥的结果:
Apple Another Hello
获取List值的结果:
3.14 Element World
Mat*_*uth 39
使用Java 8 Streams API.
List<Value> values = map.values().stream().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
man*_*esh 14
我想你想将包含的值转换Map为list?最简单的values()方法是调用Map接口的方法.这将返回Collection包含在其中的值对象Map.
请注意,这Collection由Map对象支持,对象的任何更改Map都将在此处反映出来.因此,如果您想要一个不绑定到您的Map对象的单独副本,只需创建一个新List对象,如ArrayList传递值Collection,如下所示.
ArrayList<String> list = new ArrayList<String>(map.values());
Run Code Online (Sandbox Code Playgroud)
小智 7
你可以这样做
List<Value> list = new ArrayList<Value>(map.values());
Run Code Online (Sandbox Code Playgroud)
小智 5
如果要确保结果中的值在List<Value>输入的键顺序中,则Map<Key, Value>需要以SortedMap某种方式“通过” 。
要么从具体的SortedMap实现开始(例如TreeMap),要么在将输入Map转换为SortedMap之前将其插入到中List。例如:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
Run Code Online (Sandbox Code Playgroud)
否则,您将获得Map实现所提供的任何本机排序,这通常可以是自然键排序以外的其他内容(尝试Hashtable或ConcurrentHashMap,品种)。
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
Set <Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Run Code Online (Sandbox Code Playgroud)
我们可以在列表中同时拥有键和值对。也可以通过遍历列表使用Map.Entry获取键和值。
// you can use this
List<Value> list = new ArrayList<Value>(map.values());
// or you may use
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
678486 次 |
| 最近记录: |