从流中获取最后 n 个元素元素

由网友(独行者自陶醉)分享简介:我想知道有没有替代方法I am wondering is there an alternative toList lastN = all.subList(Math.max(0, all.size() - n), all.size());使用 流a> 用法?with stream usage?推荐答案自定...

我想知道有没有替代方法

I am wondering is there an alternative to

List<X> lastN = all.subList(Math.max(0, all.size() - n), all.size());

使用 流a> 用法?

with stream usage?

推荐答案

自定义收集器可以这样写:

A custom collector can be written like this:

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);
}

并像这样使用它:

List<String> lastTen = input.stream().collect(lastN(10));
阅读全文

相关推荐

最新文章