【发布时间】:2018-10-14 00:23:44
【问题描述】:
对于流对象,是不是不能用collect方法写一个自定义的Collector对象,然后收集到另一个流对象?我最近刚刚了解了流,并试图获得尽可能多的经验,但我遇到了这个问题。
我的代码是:
// method to return how many unique letters are used in
// the Strings in the given stream
public int uniqueLetters(Stream<String> stream){
// transfer Strings to an uppercase char stream
IntStream allLets = stream.collect(IntStream::empty,
(s1, s2) -> { String toAdd = s2.toUpperCase();
IntStream cs = toAdd.chars();
IntStream.concat(s1, cs); //exception thrown on this line
}, IntStream::concat);
// use distinct on char stream and count
return (int) allLets.distinct().count();
}
此代码编译并且 collect 方法对于流中的第一个 String 运行良好,但第二次到达 IntStream.concat(s1, cs) 我得到以下异常:
java.lang.IllegalStateException: 流已经被操作或关闭
我的解释是,一旦我的第一个 String 转换为 IntStream 并且 collect 方法移动到下一个 String,我的第一个 IntStream 就会关闭。那是对的吗?为什么会这样?
这是我为自己发明的一个练习,旨在获得更多关于流和函数式编程的经验。我知道这可能不是编写此方法的最佳方式。我有兴趣知道为什么这不起作用,而不是我可以采取什么其他方法。
【问题讨论】:
标签: java java-8 functional-programming java-stream collectors