【发布时间】:2020-11-14 20:29:35
【问题描述】:
鉴于以下上下文:
public interface IAdditive<T> {
/** True if still capable to crunch. */
boolean canCrunch();
/** True if capable to crunch with B. */
boolean canCrunch(T other);
/** Returns a new T which is the sum of this and other */
T crunch(T other);
}
class A implements IAdditive<A> {
..
A crunch(A other) {...}
}
class B extends A {
...
B crunch(B other) {...}
}
class C implements IAdditive<C> {
...
C crunch(C other) {...}
}
现在我想“处理”一个实现流
/** Chrunches the streams where possible */
public Stream<A> crunchStream(Stream s) {
return s.map(...);
}
我坚持自己相当幼稚的做法:
public Set<A> collect(Stream<A> stream) {
Set<I> res = new HashSet<>();
Set<I> set = stream
.filter(IAdditive::canCrunch)
.collect(Collectors.toSet());
set.forEach(setItem -> set.stream()
.filter(concurrentItem -> concurrentItem.canCrunch(setItem))
.map(setItem::crunch)
.forEach(res::add));
return res;
}
这应该是有缺陷的。我正在展开流,添加强制复杂性,如果我希望接口以默认方法提供它,我将不得不使用 rawtypes。
我相信我可以使用一些帮助 :-)
【问题讨论】:
-
你的
collect方法中的I是什么?这是使用泛型还是您输入了错误的接口/类的名称? -
将其作为实现。应该使用'A'
-
在这种情况下您可以edit your question 相应地更新代码。
-
另外,您是否在寻找类似
public Set<A> collect(Stream<A> stream) { return stream .filter(A::canCrunch) .map(a -> a.crunch(a)) .collect(Collectors.toSet()); }的东西? -
不完全是。想想商店物品。相同的产品可以“融合”成具有更高数量属性的单一身份产品,但仅限于其盒子大小。
a.canCrunch说明了参与紧缩的一般能力(并且打电话更便宜)。a.canCrunch(a2)检查这两个候选人是否真的有效配对。
标签: java java-stream reduce