简体   繁体   中英

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?

I want to turn a Set<String> allTextFileList containing:

20150101_00b667339f32fcff37db6e89aea53065.txt
20150101_06d0e76e4782cff3ce455feecf72b80d.txt
20150301_11f706c03860068e7e736ff943525504.txt
20150301_33719f3b98081b32e9ffd3b932e1902d.txt

to a Map<String, Set<String>> textFileListBydate containing

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) .

  • classifier is a function determines how to classify object in the resulting 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. In this case, we need to use a collector that collects to a Set , ie Collectors.toSet() .

Code:

Map<String, Set<String>> textFileListBydate = 
            allTextFileList.stream()
                           .collect(groupingBy(s -> s.substring(0, s.indexOf('_')), toSet()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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