我有一个字符串,我将其转换为字符串中每个字符的ascii字符值的int流,然后将其映射回字符串并打印出每个字符。
所有这些工作,但我有一个奇怪的交互与。distinct()函数,我不太理解。
对于我的打印机(c)功能,它工作得很好,输出是:
hello d
hello c
hello b
hello a
所以它不打印第二个b但是如果我在字符串后面打印出a
本身仍然有第二个b
这种相互作用的原因是什么?
公共类MapTesting {public static void main(String [] args) {
String a = "dcbba";
a.chars().distinct().mapToObj( c -> (char) c).forEach(c -> MapTesting.printer(c));
System.out.println(a);
}
public static void printer(Character c) {
System.out.println("hello " + c);
}
}
Stream
对象不修改原始集合/对象,它们作用于副本。但更重要的是,字符串总是不可变的,所以a
将拥有你为它定义的所有内容,是的。
distinct()
在后台创建Set
,但与您似乎要问的问题无关