Mapping a list to Map Java 8 stream and groupingBy

后端 未结 1 1092
囚心锁ツ
囚心锁ツ 2021-01-04 07:46

I have this simple Bean class:

public class Book {     

public Book(Map attribute) {
    super();
    this.attribute = attribute;
}
//         


        
相关标签:
1条回答
  • 2021-01-04 08:12

    You could do it like this:

    Map<String, List<String>> library = 
        books.stream()
             .flatMap(b -> b.getAttribute().entrySet().stream())
             .collect(groupingBy(Map.Entry::getKey, 
                                 mapping(Map.Entry::getValue, toList())));
    

    From the Stream<Book>, you flat map it with the stream of each map it contains so that you have a Stream<Entry<String, String>>. From there you group the elements by the entries' key and map each entry to its value that you collect into a List for the values.

    0 讨论(0)
提交回复
热议问题