Skip to content

Instantly share code, notes, and snippets.

@fwgreen
Last active April 2, 2020 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwgreen/e391159eb2526435125404dc4d49ef63 to your computer and use it in GitHub Desktop.
Save fwgreen/e391159eb2526435125404dc4d49ef63 to your computer and use it in GitHub Desktop.
Collection utilities I tend to forget how to implement
<E> List<List<E>> chunk(List<E> list, int size) {
int length = list.size();
return IntStream.range(0, (length - 1) / size + 1)
.mapToObj(i -> list.subList(i *= size, length - size >= i ? i + size : length))
.collect(Collectors.toList());
}
<T, U> Map<T, U> zip(List<T> first, List<U> second) {
return IntStream.range(0, Math.min(first.size(), second.size())).boxed()
.collect(Collectors.toMap(first::get, second::get));
}
record Pair<K, V>(K first, V second) implements Map.Entry<K, V> {
public K getKey() { return first; }
public V getValue() { return second; }
public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment