[英]Group by a Collection of String with Stream groupingby in java8
How to use the expression Stream
groupingBy
operation of Java 8 to finish this? 如何使用表达式
Stream
groupingBy
操作Java 8来完成这个?
I want to turn a Set<String> allTextFileList
containing: 我想转一个
Set<String> allTextFileList
包含:
20150101_00b667339f32fcff37db6e89aea53065.txt
20150101_06d0e76e4782cff3ce455feecf72b80d.txt
20150301_11f706c03860068e7e736ff943525504.txt
20150301_33719f3b98081b32e9ffd3b932e1902d.txt
to a Map<String, Set<String>> textFileListBydate
containing 到
Map<String, Set<String>> textFileListBydate
包含
20150101 ->
- 20150101_00b667339f32fcff37db6e89aea53065.txt
- 20150101_06d0e76e4782cff3ce455feecf72b80d.txt
20150301 ->
- 20150301_11f706c03860068e7e736ff943525504.txt
- 20150301_33719f3b98081b32e9ffd3b932e1902d.txt
Basically, you want to group by the first part of the filename, ie the substring starting from the beginning to the first index of "_"
. 基本上,您希望按文件名的第一部分进行分组,即从开头到第一个索引
"_"
的子字符串。
For this task, you can use Collectors.groupingBy(classifier, downstream)
. 对于此任务,您可以使用
Collectors.groupingBy(classifier, downstream)
。
classifier
is a function determines how to classify object in the resulting Map
. classifier
是一个函数,用于确定如何在生成的Map
对对象进行分类。 In this case, it is the function that will return the first part of the filename. downstream
is a Collector
that reduces all the values having the same classifier. downstream
是一个Collector
,它可以减少具有相同分类Collector
所有值。 In this case, we need to use a collector that collects to a Set
, ie Collectors.toSet()
. Set
Collectors.toSet()
,即Collectors.toSet()
。 Code: 码:
Map<String, Set<String>> textFileListBydate =
allTextFileList.stream()
.collect(groupingBy(s -> s.substring(0, s.indexOf('_')), toSet()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.