Java 8如何按该集合内的列表属性对集合进行分组

时间:2019-11-14 18:10:20

标签: java java-8 collectors

因此,我有一个对象Collection的集合,该Book对象的属性之一是List风格。 我想按类型对Book对象进行分组。我知道使用Java 8流很简单,要分组的属性不是List对象。但是如何为该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] 

}
}

对不起,代码示例不好。

2 个答案:

答案 0 :(得分:3)

  

但是如何为列表中的每个元素实现此“分组”   属性。

此处的关键点是greet.js + flatMap,然后与map一起作为下游收集器。

mapping

答案 1 :(得分:1)

非流版本仅使用两个嵌套的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;})
        )
);