How to get a List from a HashMap>

后端 未结 7 645
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 04:28

I want to extract a List from a Map> (E is a random Class) using stream().

I

相关标签:
7条回答
  • 2020-12-15 04:29

    map.values() returns a Collection<List<E>> not a List<E>, if you want the latter then you're required to flatten the nested List<E> into a single List<E> as follows:

    List<E> result = map.values()
                        .stream()
                        .flatMap(List::stream)
                        .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-15 04:32

    You can use Collection.stream with flatMap as:

    Map<String, List<E>> map = new HashMap<>(); // program to interface
    List<E> list = map.values()
                      .stream()
                      .flatMap(Collection::stream)
                      .collect(Collectors.toList());
    

    or use a non-stream version as:

    List<E> list = new ArrayList<>();
    map.values().forEach(list::addAll)
    
    0 讨论(0)
  • 2020-12-15 04:33

    Here's an alternate way to do it with Java-9 and above:

    List<E> result = map.values()
                        .stream()
                        .collect(Collectors.flatMapping(List::stream, Collectors.toList()));
    
    0 讨论(0)
  • 2020-12-15 04:33

    Simply use :-

    map.values().stream().flatMap(List::stream).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-15 04:36

    In addition to other answers:

    List<E> result = map.values()
                        .stream()
                        .collect(ArrayList::new, List::addAll, List::addAll);
    

    This could also do the trick.

    0 讨论(0)
  • 2020-12-15 04:49

    Or use forEach

     map.forEach((k,v)->list.addAll(v));
    

    or as Aomine commented use this

    map.values().forEach(list::addAll);
    
    0 讨论(0)
提交回复
热议问题