我正在解决一个问题,我需要处理流中的重叠对。
例如,考虑列表 →
["lion","fox","hare","carrot"]
。
输出将是:
lion eats fox
fox eats hare
hare eats carrot.
输出项总是比原始列表少一项。我目前正在使用 Java 8。这是我的代码:
static <T,R> Function <T, Stream<R>> pairMap(BiFunction<T,T,R> mapper)
{
return new Function<> () {
T previous = null;
boolean hasPrevious;
public Stream<R> apply(T t)
{
Stream<R> result;
if(!hasPrevious)
{
hasPrevious = true;
result = Stream.empty();
}
else
{
result = Stream.of(mapper.apply(previous, t));
}
previous = t;
return result;
}
};
}
static <T> Stream<T> getAdjecentOverlappingStream(List<T> list)
{
return list.stream().flatMap(pairMap((a,b) -> a+" eats "+ b));
}
//consider the class name I am working with is StreamUtils.
StreamUtils.getAdjecentOverlappingStream(Arrays.asList("lion","fox","hare","carrot"))
.forEach(System.out::println);;
但是这段代码给了我错误错误:无法推断函数的类型参数
查看完整错误。
StreamLecture.java:83: error: cannot infer type arguments for Function<T,R>
return new Function<> () {
^
reason: cannot use '<>' with anonymous inner classes
where T,R are type-variables:
T extends Object declared in interface Function
R extends Object declared in interface Function
StreamLecture.java:106: error: incompatible types: inference variable R#1 has incompatible bounds
return list.stream().flatMap(pairMap((a,b) -> a+" eats "+ b));
^
equality constraints: T#2
lower bounds: String,R#2
where R#1,T#1,T#2,R#2,T#3 are type-variables:
R#1 extends Object declared in method <R#1>flatMap(Function<? super T#1,? extends Stream<? extends R#1>>)
T#1 extends Object declared in interface Stream
T#2 extends Object declared in method <T#2>getAdjecentOverlappingStream(List<T#2>)
R#2 extends Object declared in method <T#3,R#2>pairMap(BiFunction<T#3,T#3,R#2>)
T#3 extends Object declared in method <T#3,R#2>pairMap(BiFunction<T#3,T#3,R#2>)
Note: StreamLecture.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
如何修复此错误?
windowSliding
收集器(作为 Stream Gatherers 功能的一部分添加)可用于处理所有相邻元素对:
static Stream<String> getAdjacentOverlappingStream(List<?> list) {
return list.stream()
.gather(Gatherers.windowSliding(2))
.map(w -> w.getFirst() + " eats " + w.getLast());
}
请注意,我已将方法返回类型从
Stream<T>
更改为 Stream<String>
,因为它返回字符串流,而不是 T
类型的对象。
编译错误的原因是
list.stream().flatMap(pairMap((a,b) -> a+" eats "+ b))
返回一个Stream<String>
,但是getAdjecentOverlappingStream
方法被声明为返回Stream<T>
。 将方法的返回类型从 Stream<T>
更改为 Stream<String>
可以修复编译错误。
static <T> Stream<String> getAdjecentOverlappingStream(List<T> list)
{
return list.stream().flatMap(pairMap((a,b) -> a+" eats "+ b));
}
请注意,通过此更改,不再需要类型参数
T
,因此如果需要,可以将其更改为通配符类型 <?>
:
static Stream<String> getAdjecentOverlappingStream(List<?> list)
{
return list.stream().flatMap(pairMap((a,b) -> a+" eats "+ b));
}