man*_*pac 6 java collections set java-8 java-stream
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;
}
Run Code Online (Sandbox Code Playgroud)
如果没有以下条件,以上代码将无法编译:
.mapObj(c -> (char)c)
// <Character> Stream<Character> java.util.stream.IntStream.mapToObj(IntFunction<? extends Character> mapper)
Run Code Online (Sandbox Code Playgroud)
如果删除它,会出现以下错误
The method mapToInt((<no type> c) -> {}) is undefined for the type IntStream
Run Code Online (Sandbox Code Playgroud)
有人可以解释吗?似乎我从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();
Run Code Online (Sandbox Code Playgroud)
另外,使用Set<Integer>有助于避免转换为字符:
Set<Integer> set = new HashSet<>();
Run Code Online (Sandbox Code Playgroud)
int count = myString.chars() // IntStream
.map(c -> (set.add(c) ? 1 : 0)) // IntStream
.sum();
long count = myString.chars() // IntStream
.filter(set::add) // IntStream
.count();
Run Code Online (Sandbox Code Playgroud)
但是,无论您要实现什么目标,原则上您的代码都是错误的,确切地说,是无状态行为。考虑使用以下代码段,这些代码段的lambda表达式的结果不依赖于非确定性运算的结果,例如Set::add。
如果流操作的行为参数是有状态的,则流管道结果可能不确定或不正确。
long count = myString.chars() // IntStream
.distinct() // IntStream
.count();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |