简体   繁体   English

在java8中按字符串集合进行分组

[英]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.

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