Process adjacent overlapping pairs from the java stream

I am working on a problem that I need to process overlapping pairs from the stream.

for example, consider the list → ["lion","fox","hare","carrot"] . So output will be

lion eats fox

fox eats hare

hare eats carrot.

Output items are always one less than that of the original list. I am currently using java 8 . here’s my code

Code

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));     }  

Calling method

//consider the class name I am working with is StreamUtils.   StreamUtils.getAdjecentOverlappingStream(Arrays.asList("lion","fox","hare","carrot")) .forEach(System.out::println);; 

But this code giving me error as error: cannot infer type arguments for Function<T,R>

See full error.

Error

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 

Please help me fix this error. thanks ✌

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.