Last active
April 2, 2020 13:47
-
-
Save fwgreen/e391159eb2526435125404dc4d49ef63 to your computer and use it in GitHub Desktop.
Collection utilities I tend to forget how to implement
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
<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