如何从 Java 8 中的流中获取 Map<String, List<Object>>
How get a Map<String, List<Object>> from a Stream in Java 8
我有下一个class:
public class ExampleClass {
private String title;
private String codeResponse;
private String fileName;
}
我需要生成一个映射,其中键是文件名,值是包含该文件名的对象列表。我做了以下事情:
Map<String, List<ExampleClass>> mapValues = items
.stream()
.collect(Collectors.groupingBy(
item -> item.getFileName(),
Collectors.mapping(item -> item, Collectors.toList())
));
但在这种情况下,我在每个 fileName
中保存对象的总列表,包括那些不适用的对象。
您只需要 Collectors.groupingBy
。默认情况下,实例将放置在列表中。
Map<String, List<ExampleClass>> mapValues = items.stream()
.collect(Collectors.groupingBy(item->item.getFileName()));
您也可以使用 ExampleClass::getFileName
代替 lambda。但这是个人喜好问题。
我有下一个class:
public class ExampleClass {
private String title;
private String codeResponse;
private String fileName;
}
我需要生成一个映射,其中键是文件名,值是包含该文件名的对象列表。我做了以下事情:
Map<String, List<ExampleClass>> mapValues = items
.stream()
.collect(Collectors.groupingBy(
item -> item.getFileName(),
Collectors.mapping(item -> item, Collectors.toList())
));
但在这种情况下,我在每个 fileName
中保存对象的总列表,包括那些不适用的对象。
您只需要 Collectors.groupingBy
。默认情况下,实例将放置在列表中。
Map<String, List<ExampleClass>> mapValues = items.stream()
.collect(Collectors.groupingBy(item->item.getFileName()));
您也可以使用 ExampleClass::getFileName
代替 lambda。但这是个人喜好问题。