java8如何在集合中按列表属性对集合进行分组



所以我有一个对象集合collection,Book对象的属性之一是List types。我想按类型对我的图书对象进行分组。我知道使用java8流很简单,如果要分组的属性不是List对象。但是我如何通过对该列表属性中的每个元素进行"分组"。

String title;
String ISBN,
List<String> genres;
public static void main(String args) {
Book b1 = new Book();
b1.genres = ['Drama', 'Comedy']
Book b2 = new Book();
b2.genres = ['Factual']
Book b3 = new Book();
b3.genres = ['Factual', 'Crime']
Book b4 = new Book();
b4.genres = ['Comedy', 'Action']
//How to now group a collection of book objects by genre so I can get the following grouping:
Drama = [b1], Comedy =  [b1, b4], Factual = [b2, b3], Crime = [b3], Action = [b4] 
}
}

很抱歉代码示例不好。

但是我如何通过对列表中的每个元素进行分组来实现这种"分组"所有物

这里的关键点是flatMap+map,然后用mapping作为下游收集器进行分组。

Map<String, List<Book>> result = source.stream()
.flatMap(book -> book.getGenres().stream().map(genre -> new AbstractMap.SimpleEntry<>(genre, book)))
.collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey,
Collectors.mapping(AbstractMap.SimpleEntry::getValue,
Collectors.toList())));

而非流版本只是使用了两个嵌套的for循环。

Map<String, List<Book>> map = new HashMap<>();
listOfBook.forEach(b -> b.getGenres()
.forEach(genre ->
map.merge(genre, new ArrayList<>(Collections.singletonList(b)),
(l1, l2) -> { l1.addAll(l2);return l1;})
)
);

最新更新