Skip to content

Commit c4b5eb7

Browse files
committed
Implement groupBy on List
1 parent 9e0a6a1 commit c4b5eb7

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

core/src/main/java/fj/data/List.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,50 @@ public final A mode(final Ord<A> o) {
12371237
return sort(o).group(o.equal()).maximum(intOrd.comap(List.<A>length_())).head();
12381238
}
12391239

1240+
public final <K> HashMap<K, List<A>> groupBy(final F<A, K> keyFunction) {
1241+
return groupBy(keyFunction, Function.identity());
1242+
}
1243+
1244+
public final <K, V> HashMap<K, List<V>> groupBy(
1245+
final F<A, K> keyFunction,
1246+
final F<A, V> valueFunction) {
1247+
return this.groupBy(keyFunction, valueFunction, List.<V>nil(),
1248+
new F2<V, List<V>, List<V>>() {
1249+
@Override
1250+
public List<V> f(final V head, final List<V> tail) {
1251+
return List.cons(head, tail);
1252+
}
1253+
});
1254+
}
1255+
1256+
public final <K, V, R> HashMap<K, R> groupBy(
1257+
final F<A, K> keyFunction,
1258+
final F<A, V> valueFunction, final R groupingIdentity, final F2<V, R, R> groupingAcc) {
1259+
return this.foldLeft(
1260+
new F<HashMap<K, R>, F<A, HashMap<K, R>>>() {
1261+
@Override
1262+
public F<A, HashMap<K, R>> f(final HashMap<K, R> map) {
1263+
return new F<A, HashMap<K, R>>() {
1264+
@Override
1265+
public HashMap<K, R> f(final A element) {
1266+
final K key = keyFunction.f(element);
1267+
final V value = valueFunction.f(element);
1268+
map.set(key, map.get(key)
1269+
.map(new F<R, R>() {
1270+
@Override
1271+
public R f(final R existing) {
1272+
return groupingAcc.f(value, existing);
1273+
}
1274+
})
1275+
.orSome(groupingAcc.f(value, groupingIdentity)));
1276+
return map;
1277+
}
1278+
};
1279+
}
1280+
}, HashMap.<K, R>hashMap()
1281+
);
1282+
}
1283+
12401284
/**
12411285
* Returns whether or not all elements in the list are equal according to the given equality test.
12421286
*

0 commit comments

Comments
 (0)