Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a lambda function to iterate collections simultaneously

I'm trying Java 8, I want to iterate over 2 collections and call a parameter function for each pair of values.

In abstract, I want to apply a foo(tuple, i) function for each iteration

[ v1, v2, v3, v4, v5, v6 ] (first collection)
[ w1, w2, w3, w4, w5, w6 ] (second collection)
---------------------------
  foo(<v1,w1>, 0)
  foo(<v2,w2>, 1)
  ...
  foo(<v6,w6>, 5)

Now what I got so far (java and pseudo code)

// Type of f?
private <S,U> void iterateSimultaneously(Collection<S> c1, Collection<U> c2, Function f) {
        int i = 0
        Iterator<S> it1 = c1.iterator()
        Iterator<U> it2 = c2.iterator()
        while(it1.hasNext() && it2.hasNext()) {
            Tuple<S, U> tuple = new Tuple<>(it1.next(), it2.next())             

            // call somehow f(tuple, i)

            i++
        }
}
 // ........................

// pseudo code, is this posible in Java?
iterateSimultaneously(c1, c2, (e1, e2, i) -> {
  // play with those items and the i value
})
like image 298
Manu Avatar asked May 16 '17 09:05

Manu


1 Answers

Is something like this what you're looking for?

private <S,U> void iterateSimultaneously(Collection<S> c1, Collection<U> c2, BiConsumer<Tuple<S, U>, Integer> f) {
        int i = 0
        Iterator<S> it1 = c1.iterator()
        Iterator<U> it2 = c2.iterator()
        while(it1.hasNext() && it2.hasNext()) {
            Tuple<S, U> tuple = new Tuple<>(it1.next(), it2.next())             
            f.accept(tuple, i);
            i++
        }
}
iterateSimultaneously(c1, c2, (t, i) -> {
    //stuff
})

What type is the function f supposed to return? If nothing, change it to a consumer instead. If you want it to accept a tuple you most clarify it like I have done here. Is this what you're looking for?

like image 149
Ted Cassirer Avatar answered Oct 26 '22 23:10

Ted Cassirer