Mapping a list to Map Java 8 stream and groupingBy

后端 未结 1 1103
囚心锁ツ
囚心锁ツ 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> library = 
        books.stream()
             .flatMap(b -> b.getAttribute().entrySet().stream())
             .collect(groupingBy(Map.Entry::getKey, 
                                 mapping(Map.Entry::getValue, toList())));
    

    From the Stream, you flat map it with the stream of each map it contains so that you have a Stream>. 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)
提交回复
热议问题