Created
July 2, 2012 16:26
-
-
Save jami-i/3034096 to your computer and use it in GitHub Desktop.
This file contains 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
public interface Function<T, R> { | |
R apply(T t); | |
} | |
public interface GroupBy<E> { | |
Map<Object,List<E>> groupBy(Function<E,Object> f); | |
} | |
public class GroupByList<E> extends ArrayList<E> implements GroupBy<E> { | |
private static final long serialVersionUID = 1L; | |
public Map<Object,List<E>> groupBy(Function<E,Object> f){ | |
Map<Object,List<E>> result = new HashMap<Object,List<E>>(); | |
for(E e : this){ | |
Object key = f.apply(e); | |
List<E> list = result.get(key); | |
if(list == null){ | |
list = new ArrayList<E>(); | |
} | |
list.add(e); | |
result.put(key, list); | |
} | |
return result; | |
} | |
} | |
public class GroupByListTest { | |
public static List<Integer> oddList = new ArrayList<Integer>(); | |
{ | |
oddList.add(1); | |
oddList.add(3); | |
oddList.add(5); | |
} | |
public static List<Integer> evenList = new ArrayList<Integer>(); | |
{ | |
evenList.add(2); | |
evenList.add(4); | |
evenList.add(6); | |
} | |
@Test | |
public void test() { | |
GroupByList<Integer> intList = new GroupByList<Integer>(); | |
intList.add(1); | |
intList.add(2); | |
intList.add(3); | |
intList.add(4); | |
intList.add(5); | |
intList.add(6); | |
Map<Object, List<Integer>> groupBy = intList | |
.groupBy(new Function<Integer, Object>() { | |
@Override | |
public Object apply(Integer t) { | |
return t % 2 == 0; | |
} | |
}); | |
assertNotNull(groupBy); | |
assertThat(groupBy.get(true), is(evenList)); | |
assertThat(groupBy.get(false), is(oddList)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment