Created
June 26, 2015 14:09
-
-
Save patrickhammond/fb2f3db2611b8cb21ea4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* The smarter thing to do would be to use what is Guava, etc...but Guava is a big fat library that | |
* will blow the dex count and this is pretty much the only thing we are using out of it. | |
* | |
* No guarantee that any of these are the best implementation. | |
*/ | |
public class CollectionsUtil { | |
public interface Predicate<T> { | |
boolean apply(T object); | |
} | |
public interface IndexedPredicate<T> { | |
boolean apply(int index, T object); | |
} | |
public static <T> boolean atLeastOneMatches(List<T> list, Predicate<T> predicate) { | |
return first(list, predicate) != null; | |
} | |
public static <T> T first(List<T> list, Predicate<T> predicate) { | |
for (T item : list) { | |
if (predicate.apply(item)) { | |
return item; | |
} | |
} | |
return null; | |
} | |
public static <T> List<T> filter(List<T> list, Predicate<T> predicate) { | |
ArrayList<T> result = new ArrayList<T>(); | |
for (T item : list) { | |
if (predicate.apply(item)) { | |
result.add(item); | |
} | |
} | |
return result; | |
} | |
public static <T> List<T> filter(List<T> list, IndexedPredicate<T> predicate) { | |
ArrayList<T> result = new ArrayList<T>(); | |
for (int i = 0; i < list.size(); i++) { | |
T item = list.get(i); | |
if (predicate.apply(i, item)) { | |
result.add(item); | |
} | |
} | |
return result; | |
} | |
public interface Function<F, T> { | |
T apply(F from); | |
} | |
public static <F, T> List<T> transform(List<F> list, Function<F, T> function) { | |
ArrayList<T> result = new ArrayList<T>(); | |
if (list == null) { | |
return result; | |
} | |
for (F item : list) { | |
result.add(function.apply(item)); | |
} | |
return result; | |
} | |
public static <K, V> Map<K,V> toMap(List<V> list, Function<V, K> function) { | |
HashMap<K, V> map = new HashMap<K, V>(); | |
if (list == null) { | |
return map; | |
} | |
for (V item : list) { | |
map.put(function.apply(item), item); | |
} | |
return map; | |
} | |
public static <T> List<T> concat(List<T> a, List<T> b) { | |
ArrayList<T> result = new ArrayList<T>(); | |
result.addAll(a); | |
result.addAll(b); | |
return result; | |
} | |
public static <T> List<T> toMutableList(T...items) { | |
return new ArrayList<>(Arrays.asList(items)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment