简体   繁体   English

带有字符串列表的 Java 流 Collectors.groupingBy()

[英]Java stream Collectors.groupingBy() with list of String

I have following class :我有以下课程:

Class Foo{
  private String cassette;
  private List<String> organs; //["Lung","Liver"]
  //getter setter
}

I'm collecting data into List<Foo> and I want to group them by organ as Map<String,List<Foo>>我正在将数据收集到List<Foo> ,我想按器官将它们分组为Map<String,List<Foo>>

So far I have tried following solution:到目前为止,我已经尝试了以下解决方案:

Map<Object, List<Foo>> collect = fooList
                                   .stream()
                                   .collect(Collectors.groupingBy(x -> x.getOrgan()));

It returns Map<Object, List<Foo>> instead of Map<String,List<Foo>> as follow:它返回Map<Object, List<Foo>>而不是Map<String,List<Foo>>如下:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver]]], [Liver]=[Foo [cassette=2A, organ=[Liver]]]} {[肺,肝]=[Foo [盒=1A,器官=[肺,肝脏]]],[肝脏]=[Foo [盒=2A,器官=[肝脏]]]}

Also, how can I make a generic method which will return Map<String,List<Foo>> when I pass only key for grouping of Type<T> for Collectors.groupingBy(T) and it will group by a specified key另外,当我只传递用于对Collectors.groupingBy(T)进行分组的Type<T>键时,如何创建一个返回Map<String,List<Foo>>的通用方法,并且它将按指定的键进行分组

You are grouping by a List<String> , not by a String .您按List<String>分组,而不是按String分组。 To group by a String you have to pre-process the Stream to first obtain all the pairs of (String,Foo):要按String分组,您必须对Stream进行预处理以首先获取所有 (String,Foo) 对:

Map<String,List<Foo>> collect = 
    fooList.stream()
           .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o,f)))
           .collect(Collectors.groupingBy(Map.Entry::getKey,
                                          Collectors.mapping(Map.Entry::getValue,
                                                             Collectors.toList())));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM