Last active
January 16, 2018 23:38
-
-
Save flaviut/3157889522e27221adab5e195ad7f5aa to your computer and use it in GitHub Desktop.
groupby for java 6 & 7
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
/** | |
* A generic interface for an one-element lambda | |
*/ | |
private interface Predicate<P1, R> { | |
R apply(P1 p1); | |
} | |
private static <T, C> List<List<T>> groupBy(Collection<T> collection, | |
Predicate<? super T, C> byValue) { | |
// PRECONDITION collection and byValue must not be null | |
// PRECONDITION collection must be sorted by the value byValue returns | |
// PRECONDITION byValue must never return null | |
C currentItem = null; | |
List<List<T>> result = new ArrayList<List<T>>(); | |
for (T item : collection) { | |
C itemValue = byValue.apply(item); | |
if (itemValue == null) { | |
throw new RuntimeException("byValue must never return null"); | |
} | |
if (currentItem != itemValue) { | |
currentItem = itemValue; | |
result.add(new ArrayList<T>()); | |
} | |
result.get(result.size() - 1).add(item); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment