Combining two Iterables using standard library -- or -- map with multiple Iterables

Go To StackoverFlow.com

4

When given two Iterables

val keys = newLinkedList('foo', 'bar', 'bla')
val vals = newLinkedList(42, 43, 44)

I want to correlate each item in both lists like this:

val Iterable<Pair<String, Integer>> expected 
    = newLinkedList('foo'->42, 'bar'->43, 'bla'->44)

OK, I could do it by hand iterating over both lists.

On the other hand this smells like something where

  • some standard function is available in Xtend or guava or
  • some neat trick will do it in one line.

For examples in Python this would be a no-brainer, because their map function can take multiple lists.

How can this be solved using Xtend2+ with miniumum code?

2012-04-05 22:06
by A.H.
http://code.google.com/p/guava-libraries/wiki/IdeaGraveyard discusses why Guava does not provide a Pair type - Louis Wasserman 2012-04-05 23:52
I think that's the kind of code that's actually more readable when written in an imperative style.

"Excessive use of Guava's functional programming idioms can lead to verbose, confusing, unreadable, and inefficient code. These are by far the most easily (and most commonly) abused parts of Guava, and when you go to preposterous lengths to make your code "a one-liner," the Guava team weeps. " ( http://code.google.com/p/guava-libraries/wiki/FunctionalExplained - Etienne Neveu 2012-04-06 08:18

@LouisWasserman: Please note, that the question is basically about Xtend, a functional language, which uses Guava internally. IN Xtend you have Pair embedded into the language. This is what the x->y operator does. So I think guava's philosophy does not apply in this case - A.H. 2012-04-06 09:09
@eneveu: Please note, that the question is basically about Xtend, a functional language, which uses Guava internally. In Xtend code like val paired = zip(keys, vals)[k, v | k -> v] would be more readable than doing it by hand. What I want to know: IS there something like this zip thing on board somewhere - A.H. 2012-04-06 09:15


7

final Iterator it = vals.iterator();
expected = Iterables.transform(keys, new Function<String, Pair>() {
    public Pair apply(String key) {
        return new Pair(key, it.next());
    }
});

Added by A.H.:

In Xtend this looks like this:

val valsIter = vals.iterator()
val paired = keys.map[ k | k -> valsIter.next ]
2012-04-05 22:22
by Andrejs
Ads