Skip to content

Instantly share code, notes, and snippets.

@rdemorais
Created November 23, 2019 18:43
Show Gist options
  • Save rdemorais/d98aa992d765a741b9cb5b1c8f10cc58 to your computer and use it in GitHub Desktop.
Save rdemorais/d98aa992d765a741b9cb5b1c8f10cc58 to your computer and use it in GitHub Desktop.
public static <T> Collector<T, ?, List<T>> lastN(int n) {
return Collector.<T, Deque<T>, List<T>>of(ArrayDeque::new, (acc, t) -> {
if(acc.size() == n)
acc.pollFirst();
acc.add(t);
}, (acc1, acc2) -> {
while(acc2.size() < n && !acc1.isEmpty()) {
acc2.addFirst(acc1.pollLast());
}
return acc2;
}, ArrayList::new);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment