如何将List <obj1>转换为Map <obj1.prop,list <obj1.otherprop =“”>

时间:2018-06-28 09:17:11

标签: java java-8 java-stream

如何使用流将列表转换为列表地图?

我想将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(). ...
                                                                ^^^

1 个答案:

答案 0 :(得分:7)

使用Collectors.mapping将每个Book映射到其对应的标题:

Map<String, List<String>> map = bookList.stream()
    .collect(Collectors.groupingBy(book -> book.getAuthor().getFirstName(),
                                   Collectors.mapping(Book::getTitle,Collectors.toList())));