I'm currently struggling with the following excercise:
Given a
Stream<String>
collect (usingCollector
) a Collection of allString
s with maximum lenght.
Here is what I tried:
private static class MaxStringLenghtCollector
implements Collector<String, List<String>, List<String>> {
@Override
public Supplier<List<String>> supplier() {
return LinkedList::new;
}
@Override
public BiConsumer<List<String>, String> accumulator() {
return (lst, str) -> {
if(lst.isEmpty() || lst.get(0).length() == str.length())
lst.add(str);
else if(lst.get(0).length() < str.length()){
lst.clear();
lst.add(str);
}
};
}
@Override
public BinaryOperator<List<String>> combiner() {
return (lst1, lst2) -> {
lst1.addAll(lst2);
return lst1;
};
}
@Override
public Function<List<String>, List<String>> finisher() {
return Function.identity();
}
@Override
public Set<java.util.stream.Collector.Characteristics> characteristics() {
return EnumSet.of(Characteristics.IDENTITY_FINISH);
}
}
So I wrote my custom collector which does the job but... it really does look ugly. Maybe there's some standard way to do that. For instance, I'd try the grouping collector:
public static Collection<String> allLongest(Stream<String> str){
Map<Integer, List<String>> groups = str.collect(Collectors.groupingBy(String::length));
return groups.get(groups.keySet()
.stream()
.mapToInt(x -> x.intValue())
.max()
.getAsInt());
}
But this is ugly as well as inefficient. First, we build a Map
, then travesrse it to build a Set
and then traverse it get the max-List
.