mancocapac:
public static int construction(String myString) {
Set<Character> set = new HashSet<>();
int count = myString.chars() // returns IntStream
.mapToObj(c -> (char)c) // Stream<Character> why is this required?
.mapToInt(c -> (set.add(c) == true ? 1 : 0)) // IntStream
.sum();
return count;
}
上記のコードは、なしでコンパイルされません。
.mapObj(c -> (char)c)
// <Character> Stream<Character> java.util.stream.IntStream.mapToObj(IntFunction<? extends Character> mapper)
私はそれを削除した場合、私は次のエラーを取得します
The method mapToInt((<no type> c) -> {}) is undefined for the type IntStream
誰かがこれを説明することはできますか?私はIntStreamに戻って、次に文字ストリームに変換し、そしてIntStreamを始めていますように思えます。
ニコラス:
この方法は、CharSequence::chars
返しIntStream
のような、もちろんintに変換する任意の方法を提供しないが、mapToInt
しかし、mapToObj
その代わり。したがって、方法IntStream::map(IntUnaryOperator mapper)
の両方が戻りをとるint
よくために使用されなければならないようにIntUnaryOperator
ように同じことをFunction<Integer, Integer>
、またはUnaryOperator<Integer>
。
int count = myString.chars() // IntStream
.map(c -> (set.add((char) c) ? 1 : 0)) // IntStream
.sum();
long count = myString.chars() // IntStream
.filter(c -> set.add((char) c)) // IntStream
.count();
また、使用するには、Set<Integer>
あなたが文字への変換を避けるために役立ちます。
Set<Integer> set = new HashSet<>();
int count = myString.chars() // IntStream
.map(c -> (set.add(c) ? 1 : 0)) // IntStream
.sum();
long count = myString.chars() // IntStream
.filter(set::add) // IntStream
.count();
しかし、関係なく、あなたが達成しようとするものの、あなたのコードは原則によって間違っている、NOステートレス行動は、正確には。ラムダ式の結果ではない次のスニペット使用することを検討してください依存非決定論的操作の結果について、などをSet::add
。
ストリーム操作に行動パラメーターがステートフルである場合に、ストリームパイプラインの結果が非決定的か間違っている可能性があります。
long count = myString.chars() // IntStream
.distinct() // IntStream
.count();