convert map to list - as “key-value” to each list entry

后端 未结 4 1258
Happy的楠姐
Happy的楠姐 2021-01-14 09:16

I want to convert Map to List with each map entry - to 1 entry in the list as \"key - value\"

I search

相关标签:
4条回答
  • 2021-01-14 09:25

    if you want just the values of the Map try this

    List<String> list = new ArrayList<>(map.values())
    

    {"apple", "orange"}

    0 讨论(0)
  • 2021-01-14 09:40
        List<String> list = map.entrySet()
                                .stream()
                                .map(entry -> entry.getKey() + "-" + entry.getValue())
                                .sorted()
                                .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-01-14 09:41

    Just a slightly different variant to the other answers. if the insertion/iteration order is important then I'd rather use a LinkedHashMap in the first place as opposed to using a HashMap then sorting it which is actually not always guaranteed to work.

    Example:

    Map<Integer, String> map = new LinkedHashMap<>();
    ...
    ...
    ...
    

    then stream over the entrySet and collect to a list implementation:

    List<String> list = map.entrySet()
                            .stream()
                            .map(e -> e.getKey() + "-" + e.getValue())
                            .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-01-14 09:47

    Here is one variant using .map to move from list to map

    List<String> list = map.entrySet()
                           .stream()
                           .map(x -> String.format("%d-%s", x.getKey().intValue(), x.getValue()))
                           .sorted().collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题