I have a problem of collecting some list values to buckets. For example, let's assume I have a list of Strings:
List<String> strs = Arrays.asList("ABC", "abc", "bca", "BCa", "AbC");
And I want to put the strings into set (or list) of sets, that contain only case-different strings, i.e. for example above it would be collection of two sets: [["ABC", "abc", "AbC"], ["bca", "BCa"]]
So help me please to write collector for this problem.
List<Set<String>> result = strs.stream()
.collect(/* some collectors magic here */)
The "some collectors magic" you are looking for can be done in two steps:
String#toLowerCase
does the job (don't forget the overloaded method that takes a Locale
as parameter). You also want the values grouped to be unique so you can use the overloaded version of groupingBy
to put them into a Set
(the default implementation uses a List
)collectingAndThen
collector.import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toSet;
...
List<Set<String>> result =
strs.stream()
.collect(collectingAndThen(groupingBy(String::toLowerCase, toSet()),
m -> new ArrayList<>(m.values())));
Try:
List<Set<String>> result =
strs.stream()
.collect(groupingBy(String::toLowerCase, toSet())) // Map<String, Set<String>>
.values() // Collection<Set<String>>
.stream() // Stream<Set<String>>
.collect(toList()); // List<Set<String>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With