开发者

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

开发者 https://www.devze.com 2023-01-28 15:05 出处:网络
I have a LinkedHashMap < String, String > map . List < String > keyList; List < String &开发者_运维百科gt; valueList;

I have a LinkedHashMap < String, String > map .

List < String > keyList;
List < String &开发者_运维百科gt; 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?


Most collections accept Collection as a constructor argument:

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


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


A different approach using 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 Object considering collection (here the map) as source

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

0

精彩评论

暂无评论...
验证码 换一张
取 消