TimurMahammadov / google-collections

Automatically exported from code.google.com/p/google-collections
Apache License 2.0
0 stars 0 forks source link

Add 'flatMap' (flatTransform?) operation #34

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Scala's collections library has an operation called 'flatMap' on its
sequence type.  It is described as:

override def flatMap[B](f : (A) => Iterable[B]) : Seq[B]

    Applies the given function f to each element of this sequence, then
concatenates the results.

I believe I've seen something similar in the ML libraries and in Haskell.

Here's a naive simple implementation:

    public static <A, B> Collection<B> flatTransform(Iterable<A>
collection, Function<A, Iterable<B>> functor) {
        ArrayList<B> results = Lists.newArrayList();
        for (A a : collection) {
            Iterable<B> result = functor.apply(a);
            Iterables.addAll(results, result);
        }

        return results;
    }

Original issue reported on code.google.com by ryan.daum on 1 Nov 2007 at 11:36

GoogleCodeExporter commented 9 years ago
There's a two-line implementation in terms of methods we already provide:

  public static <A, B> Iterable<B> flatTransform(Iterable<A> collection,
      Function<A, Iterable<B>> functor) {
    Iterable<Iterable<B>> iterables = Iterables.transform(collection, functor);
    return Iterables.concat(iterables);
  }

I don't see any pressing reason to add flatMap to the library.

Original comment by jared.l....@gmail.com on 1 Nov 2007 at 11:59

GoogleCodeExporter commented 9 years ago
Fair enough that it can be done in two lines, but why not have it there for 
others to
make use of?

Original comment by ryan.daum on 2 Nov 2007 at 12:19

GoogleCodeExporter commented 9 years ago
Because that way lies madness.

We only want to provide two-liner convenience methods for the things users do 
very,
very, very, very often.  See also

http://code.google.com/p/google-collections/issues/detail?id=18

Original comment by kevin...@gmail.com on 2 Nov 2007 at 12:26