将列表映射到Map Java 8流和groupingBy

dam*_*man 10 java collections lambda java-8

我有这个简单的Bean类:

public class Book {     

public Book(Map<String, String> attribute) {
    super();
    this.attribute = attribute;
}
//key is isbn, val is author
private Map<String, String> attribute;

public Map<String, String> getAttribute() {
    return attribute;
}
public void setAttribute(Map<String, String> attribute) {
    this.attribute = attribute;
}

}
Run Code Online (Sandbox Code Playgroud)

在我的主要课程中,我向List添加了一些信息:

    Map<String, String> book1Details = new HashMap<String, String>();
    book1Details.put("1234", "author1");
    book1Details.put("5678", "author2");
    Book book1 = new Book(book1Details);

    Map<String, String> book2Details = new HashMap<String, String>();
    book2Details.put("1234", "author2");
    Book book2 = new Book(book2Details);

    List<Book> books = new ArrayList<Book>();
    books.add(book1);
    books.add(book2);
Run Code Online (Sandbox Code Playgroud)

现在我想将图书列表转换为此表单的地图:

Map<String, List<String>>
Run Code Online (Sandbox Code Playgroud)

这样输出(上图)就像:

//isbn: value1, value2
1234: author1, author2
5678: author1
Run Code Online (Sandbox Code Playgroud)

因此,我需要将isbn作为关键字和作者作为值进行分组.一个isbn可以有多个作者.

我想尝试如下:

Map<String, List<String>> library = books.stream().collect(Collectors.groupingBy(Book::getAttribute));
Run Code Online (Sandbox Code Playgroud)

bean的格式无法更改.如果bean有字符串值而不是map,我可以做到,但坚持使用地图.

我已经编写了传统的java 6/7正确的方法,但尝试通过Java 8新功能来实现.感谢帮助.

Ale*_* C. 13

你可以这样做:

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

Stream<Book>,你平面映射它与它包含的每个地图的流,以便你有一个Stream<Entry<String, String>>.从那里,您可以按条目键对元素进行分组,并将每个条目映射到您收集到值的List中的值.