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?

A.H.
  • 63,967
  • 15
  • 92
  • 126
  • http://code.google.com/p/guava-libraries/wiki/IdeaGraveyard discusses why Guava does not provide a Pair type. – Louis Wasserman Apr 05 '12 at 23:52
  • 1
    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 Apr 06 '12 at 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. Apr 06 '12 at 09:09
  • 1
    @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. Apr 06 '12 at 09:15

1 Answers1

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 ]
A.H.
  • 63,967
  • 15
  • 92
  • 126
Andrejs
  • 26,885
  • 12
  • 107
  • 96