Skip to content

Commit f00ea5a

Browse files
committed
Adding toCollection
1 parent 108f631 commit f00ea5a

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.jnape.palatable.lambda.functions.builtin.fn1;
2+
3+
import com.jnape.palatable.lambda.functions.Fn1;
4+
import com.jnape.palatable.lambda.functions.Fn2;
5+
6+
import java.util.Collection;
7+
import java.util.function.Supplier;
8+
9+
/**
10+
* Given a {@link Supplier} of some {@link Collection} <code>C</code>, create an instance of <code>C</code> and add
11+
* all of the elements in the provided <code>Iterable</code> to the instance. Note that instances of <code>C</code>
12+
* must support {@link Collection#add} (which is to say, must not throw on invocation).
13+
*
14+
* @param <A> the iterable element type
15+
* @param <C> the resulting collection type
16+
*/
17+
public final class ToCollection<A, C extends Collection<A>> implements Fn2<Supplier<C>, Iterable<A>, C> {
18+
19+
private static final ToCollection INSTANCE = new ToCollection();
20+
21+
private ToCollection() {
22+
}
23+
24+
@Override
25+
public C apply(Supplier<C> cSupplier, Iterable<A> as) {
26+
C c = cSupplier.get();
27+
as.forEach(c::add);
28+
return c;
29+
}
30+
31+
@SuppressWarnings("unchecked")
32+
public static <A, C extends Collection<A>> ToCollection<A, C> toCollection() {
33+
return INSTANCE;
34+
}
35+
36+
public static <A, C extends Collection<A>> Fn1<Iterable<A>, C> toCollection(Supplier<C> cSupplier) {
37+
return ToCollection.<A, C>toCollection().apply(cSupplier);
38+
}
39+
40+
public static <A, C extends Collection<A>> C toCollection(Supplier<C> cSupplier, Iterable<A> as) {
41+
return toCollection(cSupplier).apply(as);
42+
}
43+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.jnape.palatable.lambda.functions.builtin.fn1;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.Collection;
7+
import java.util.function.Supplier;
8+
9+
import static com.jnape.palatable.lambda.functions.builtin.fn1.ToCollection.toCollection;
10+
import static java.util.Arrays.asList;
11+
import static org.junit.Assert.assertEquals;
12+
13+
public class ToCollectionTest {
14+
15+
@Test
16+
public void convertsIterablesToCollectionInstance() {
17+
Supplier<Collection<Integer>> listFactory = ArrayList::new;
18+
assertEquals(asList(1, 2, 3), toCollection(listFactory, asList(1, 2, 3)));
19+
}
20+
}

0 commit comments

Comments
 (0)