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

后端 未结 3 1407
-上瘾入骨i
-上瘾入骨i 2021-02-18 23:33

I have a LinkedHashMap < String, String > map .

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

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


        
相关标签:
3条回答
  • 2021-02-18 23:48

    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

    0 讨论(0)
  • 2021-02-18 23:51

    Most collections accept Collection as a constructor argument:

    List<String> keyList = new ArrayList<String>(map.keySet());
    List<String> valueList = new ArrayList<String>(map.values());
    
    0 讨论(0)
  • 2021-02-19 00:03

    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 讨论(0)
提交回复
热议问题