如何将 List<Obj1> 转换为 Map<Obj1.prop, List<Obj1.otherProp> >?

3
如何使用流将列表转换为列表映射?
我想将List<Obj>转换为Map<Obj.aProp,List<Obj.otherProp>>,而不仅仅是将List<Obj>转换为Map<Obj.aProp,List<Obj>>
class Author {
    String firstName;
    String lastName;
    // ...
}

class Book {
    Author author;
    String title;
    // ...
}

这是我想要转换的列表:
List<Book> bookList = Arrays.asList(
        new Book(new Author("first 1", "last 1"), "book 1 - 1"),
        new Book(new Author("first 1", "last 1"), "book 1 - 2"),
        new Book(new Author("first 2", "last 2"), "book 2 - 1"),
        new Book(new Author("first 2", "last 2"), "book 2 - 2")
);

我知道如何做到这一点:
// Map<Author.firstname, List<Book>> map = ...
Map<String, List<Book>> map = bookList.stream()
    .collect(Collectors.groupingBy(book -> book.getAuthor().getFirstName()));

但我应该怎么做才能获得这个:

// Map<Author.firstname, List<Book.title>> map2 = ...
Map<String, List<String>> map2 = new HashMap<String, List<String>>() {
    {
        put("first 1", new ArrayList<String>() {{
            add("book 1 - 1");
            add("book 1 - 2");
        }});
        put("first 2", new ArrayList<String>() {{
            add("book 2 - 1");
            add("book 2 - 2");
        }});
    }
}; 

// Map<Author.firstname, List<Book.title>> map2 = ...
Map<String, Map<String, List<String>> map2 = bookList.stream(). ...
                                                                ^^^

4
可能是按属性对对象列表进行分组:Java的重复问题。 - Lino
1个回答

7
使用Collectors.mapping将每本书映射到其对应的标题:
Map<String, List<String>> map = bookList.stream()
    .collect(Collectors.groupingBy(book -> book.getAuthor().getFirstName(),
                                   Collectors.mapping(Book::getTitle,Collectors.toList())));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接