Get last element of Stream/List in a one-liner

前端 未结 7 2090
时光取名叫无心
时光取名叫无心 2020-12-04 15:50

How can I get the last element of a stream or list in the following code?

Where data.careas is a List:

CArea f         


        
7条回答
  •  旧时难觅i
    2020-12-04 16:39

    If you need to get the last N number of elements. Closure can be used. The below code maintains an external queue of fixed size until, the stream reaches the end.

        final Queue queue = new LinkedList<>();
        final int N=5;
        list.stream().peek((z) -> {
            queue.offer(z);
            if (queue.size() > N)
                queue.poll();
        }).count();
    

    Another option could be to use reduce operation using identity as a Queue.

        final int lastN=3;
        Queue reduce1 = list.stream()
        .reduce( 
            (Queue)new LinkedList(), 
            (m, n) -> {
                m.offer(n);
                if (m.size() > lastN)
                   m.poll();
                return m;
        }, (m, n) -> m);
    
        System.out.println("reduce1 = " + reduce1);
    

提交回复
热议问题