【发布时间】:2016-05-24 15:04:35
【问题描述】:
我目前正在努力进行以下练习:
给定一个
Stream<String>收集(使用Collector)所有Strings 的集合 最大长度。
这是我尝试过的:
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);
}
}
所以我写了我的自定义收集器来完成这项工作,但是......它看起来确实很丑。也许有一些标准的方法可以做到这一点。例如,我会尝试分组收集器:
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());
}
但这既丑陋又低效。首先,我们构建一个Map,然后遍历它构建一个Set,然后遍历它得到max-List。
【问题讨论】:
-
我相信这回答了您的问题stackoverflow.com/questions/29334404/… 您可以将答案与比较字符串长度的比较器一起使用。但是,是的,如果你想一次性完成,你需要有一个自定义收集器。