Java - 将 LinkedHashMap 键/值放入相应列表的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4328146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:56:41  来源:igfitidea点击:

Java - Simple way to put LinkedHashMap keys/values into respective Lists?

javalistdictionarycollectionslinkedhashmap

提问by

I have a LinkedHashMap < String, String > map.

我有一个LinkedHashMap < String, String > map.

List < String > keyList;
List < String > valueList;

map.keySet();
map.values();

Is there an easy way to populate keyList from map.keySet() and valueList from map.values(), or do I have to iterate?

有没有一种简单的方法可以从 map.keySet() 填充 keyList 和从 map.values() 填充 valueList,或者我必须迭代?

采纳答案by Bozho

Most collections accept Collectionas a constructor argument:

大多数集合都接受Collection作为构造函数参数:

List<String> keyList = new ArrayList<String>(map.keySet());
List<String> valueList = new ArrayList<String>(map.values());

回答by Victor Parmar

For sure!

当然!

keyList.addAll(map.keySet());

Or you could pass it at the time of creation as well

或者你也可以在创建时传递它

List<String> keyList = new ArrayList<String>(map.KeySet());

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

回答by Razib

A different approach using java 8 -

使用 java 8 的不同方法 -

List<String> valueList = map.values().stream().collect(Collectors.toList()); 
List<String> keyList = map.keySet().stream().collect(Collectors.toList());  

Notes:

笔记:

  • stream()- returns sequence of Objectconsidering collection (here the map) as source

  • Collectors- Collectors are used to combining the result of processing on the elements of a stream.

  • stream()- 返回Object考虑集合(这里是map)作为源的 序列

  • Collectors- 收集器用于组合流元素的处理结果。