2

I have a Stream<A> of n+1elements and a functions B map(A a1,A a2) which takes two elements of A and returns one element of B. Now I want to get a Stream<B> of nelements such that the i-th element of the new stream is the result of map(a[i],a[i+1]) (here I used the square brackets of course informally). How would you do that?

Bonus: Is there even a more general solution which converts a Stream<A> of n-m+1elements using a function B map(A a1,A a2,...,A am) to a Stream<B> of nelements?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73

1 Answers1

4

Well you can use my library StreamEx which has a function exactly to solve your first task:

Stream<A> src = //...
Stream<B> res = StreamEx.of(src).pairMap(this::map);

Internally there's a custom spliterator behind this function. So if you don't want an additional dependency, you can just implement similar spliterator in your project.

I did not implement more general solution for bonus task due to many reasons. However there's a similar function in protonpack library. Via this library your task can be solved as:

Stream<B> res = StreamUtils.windowed(src, 2).map(l -> map(l.get(0), l.get(1)));

It cannot parallelize though. My spliterator parallelizes pretty well.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • 2
    Using protonpack, it should looks like `StreamUtils.windowed(Stream.of(1, 2, 3), 2).map(l -> map(l.get(0), l.get(1))).forEach(System.out::println);` which outputs, for example, `1_2` and `2_3` if the map function is `return a1+"_"+a2;` And it should works for the OP "Bonus" interrogation as well, by adjusting the window's size parameter. – Alexis C. May 18 '15 at 17:36
  • 1
    Added protonpack code example. Yes, I meant that protonpack can solve the bonus task. I focus on performance and parallelism, so I dislike creating intermediate lists. – Tagir Valeev May 18 '15 at 17:55