2
ですべての文字列のリストを収集:Stream<String>
考える私は現在、次のエクササイズで苦労していた最大の長さ
は(
Collector
を使用して)最大な長さを持つすべてのString
の のコレクションを収集します。ここで
私が試したものです:
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
を作成し、それをtravesrseしてSet
を作成し、それをトラバースして最大-を取得します。
私はこれがあなたの質問に答えると信じhttp://stackoverflow.com/questions/29334404/how-to- force-max-to-return-all-java-stream-in-a-java-stream Stringの長さを比較するコンパレータで、そこの答えを使用することができます。しかし、はい、それをワンパスしたい場合は、カスタムコレクタを用意する必要があります。 – Tunaki