Skip to content

Instantly share code, notes, and snippets.

@rawnly
Created December 20, 2020 23:50
Show Gist options
  • Save rawnly/b134f10decf02a9c0f7558c0593e21d0 to your computer and use it in GitHub Desktop.
Save rawnly/b134f10decf02a9c0f7558c0593e21d0 to your computer and use it in GitHub Desktop.
package com.federicovitale.bookmytrack.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
public class Grouper<Z, T> {
private Function<T, Z> getter;
private List<T> list;
public static <T, Z> HashMap<Z, List<T>> group(Function<T, Z> extractor, List<T> input) {
HashMap<Z, List<T>> map = new HashMap<>();
input.forEach(t -> {
List<T> list = new ArrayList<>();
list.add(t);
Optional
.ofNullable(map.putIfAbsent(extractor.apply(t), list))
.ifPresent(l -> l.add(t));
});
return map;
}
public static <T, Z> HashMap<Z, List<T>> group(List<T> input, Function<T, Z> extractor) {
HashMap<Z, List<T>> map = new HashMap<>();
input.forEach(t -> {
List<T> list = new ArrayList<>();
list.add(t);
Optional
.ofNullable(map.putIfAbsent(extractor.apply(t), list))
.ifPresent(l -> l.add(t));
});
return map;
}
public static <T, Z, M> HashMap<Z, List<M>> group(List<T> input, Function<List<T>, List<M>> mapper, Function<M, Z> extractor) {
HashMap<Z, List<M>> map = new HashMap<>();
List<M> mappedList = mapper.apply(input);
mappedList.forEach(t -> {
List<M> list = new ArrayList<>();
list.add(t);
Optional
.ofNullable(map.putIfAbsent(extractor.apply(t), list))
.ifPresent(l -> l.add(t));
});
return map;
}
public Grouper(Function<T, Z> getter, List<T> list) {
this.getter = getter;
this.list = list;
}
public HashMap<Z, List<T>> get() {
return Grouper.group(getter, list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment