Commits

Sergei Vavinov committed 3cdc7f5

flatten

Comments (0)

Files changed (5)

src/main/java/ru/yandex/bolts/collection/CollectionF.java

     CollectionF<E> tee(Function1V<? super CollectionF<E>> f);
 
     ListF<ListF<E>> paginate(int pageSize);
+
+    /**
+     * A fluent-style friendly variant of Cf.flatten().  It is an unsafe method in that
+     * it requires you to specify a correct generic type.
+     *
+     * CollectionF<CollectionF<A>> coll = ...;
+     * CollectionF<A> = coll.<A>flatten();
+     */
+    <F> ListF<F> flatten();
 } //~

src/main/java/ru/yandex/bolts/collection/CollectionsF.java

 import ru.yandex.bolts.function.Function1B;
 import ru.yandex.bolts.function.Function2;
 import ru.yandex.bolts.function.Function2I;
+import ru.yandex.bolts.function.misc.IntegerF;
 
 /**
  * Utilities to create extended collections.
     public static <T> T p3() {
         throw new RuntimeException("weaving must be enabled");
     }
+
+    public static <T> ListF<T> flatten(Collection<? extends Collection<T>> l) {
+        return Cf.x(l).flatMap(Function.<Collection<T>>identityF());
+    }
 } //~

src/main/java/ru/yandex/bolts/collection/CollectionsFTest.java

                 Cf.list(0, 7),
                 Cf.list(), Cf.list()), positiveIntegers);
     }
+
+    public void testFlatten() {
+        assertEquals(Cf.list(1, 2, 3, 4), Cf.flatten(Cf.list(Cf.list(1, 2), Cf.list(3, 4))));
+    }
 } //~

src/main/java/ru/yandex/bolts/collection/impl/AbstractCollectionF.java

     public ListF<ListF<E>> paginate(int pageSize) {
         return iterator().paginate(pageSize).toList();
     }
+
+    @Override
+    public <F> ListF<F> flatten() {
+        return Cf.flatten((CollectionF<? extends Collection<F>>) this);
+    }
 } //~

src/main/java/ru/yandex/bolts/collection/impl/AbstractCollectionFTest.java

 import ru.yandex.bolts.collection.Cf;
 import ru.yandex.bolts.collection.CollectionF;
 import ru.yandex.bolts.collection.CollectionsF;
-import ru.yandex.bolts.collection.IteratorF;
 import ru.yandex.bolts.collection.ListF;
 import ru.yandex.bolts.collection.MapF;
 import ru.yandex.bolts.function.Function;
                 Cf.list(1, 2, 3, 4).paginate(2));
         assertEquals(Cf.<ListF<Integer>>list(), Cf.<Integer>list().paginate(3));
     }
+
+    public void testFlatten() {
+        CollectionF<? extends CollectionF<String>> coll = Cf.list(Cf.list("a", "b"), Cf.list("c"));
+        assertEquals(Cf.list("a", "b", "c"), coll.<String>flatten());
+    }
+
 } //~