Fureeish:
私が収集し、すべてのJavaストリームを使用しようとしていますString
私のリストからの最大の長さのS:
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");
List<String> longest = strings.stream()
.sorted(Comparator.comparingInt(String::length).reversed())
.takeWhile(???)
.collect(Collectors.toList());
私は私が望むlongest
含むように{"long word", "long wwww", "llll wwww"}
それらがあるので、String
最大の長さを持っているの。唯一の1有する場合にはString
、最大の長さとSを、私は明らかに期待していたList
だけで、その要素を含むように。
私は最大の長さは、最初の要素に表示されていために、第1ソート彼らにしようとしたが、私は、ストリームの最初の要素の長さを取得することができません。私のような何かを試みることができますpeek()
:
static class IntWrapper {
int value;
}
public static void main(String[] args) throws IOException {
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");
IntWrapper wrapper = new IntWrapper();
List<String> longest = strings.stream()
.sorted(Comparator.comparingInt(String::length).reversed())
.peek(s -> {
if (wrapper.value < s.length()) wrapper.value = s.length();
})
.takeWhile(s -> s.length() == wrapper.value)
.collect(Collectors.toList());
System.out.println(longest);
}
それはだ... 醜いですか?私はダミーのラッパーの導入好きではない(、ありがとう効果的に最終または要件)peek()
ハック。
これを達成するための任意のよりエレガントな方法はありますか?
イリヤ・ルイセンコ:
これを試して:
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");
List<String> longest = strings.stream()
.collect(groupingBy(String::length, TreeMap::new, toList()))
.lastEntry()
.getValue();
System.out.println(longest);
出力:
[long word, long wwww, llll wwww]