java 8 如何在集合中按列表 属性 对集合进行分组
java 8 how to group a collection by list property within that collection
所以我有一个对象集合,该 Book 对象的属性之一是 List genres。
我想按流派对我的 Book 对象进行分组。我知道这很简单,使用 java 8 个流,分组依据的 属性 不是 List 对象。但是我怎样才能通过列表 属性.
中的每个元素实现这个 'grouping'
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]
}
}
对于糟糕的代码示例,我们深表歉意。
but how can I achieve this 'grouping' by for each element in that list
property.
这里的关键点是 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;})
)
);
所以我有一个对象集合,该 Book 对象的属性之一是 List genres。 我想按流派对我的 Book 对象进行分组。我知道这很简单,使用 java 8 个流,分组依据的 属性 不是 List 对象。但是我怎样才能通过列表 属性.
中的每个元素实现这个 'grouping'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]
}
}
对于糟糕的代码示例,我们深表歉意。
but how can I achieve this 'grouping' by for each element in that list property.
这里的关键点是 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;})
)
);