Created
November 23, 2019 18:43
-
-
Save rdemorais/d98aa992d765a741b9cb5b1c8f10cc58 to your computer and use it in GitHub Desktop.
Last N Stream Java from (https://stackoverflow.com/questions/30476127/get-last-n-elements-from-stream)
This file contains hidden or 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
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