Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip only nth element in java stream

In a given list of Integer, I want to skip one element at nth index.

Input:

{ 1, 2, 3, 4, 5 }

Expected output after skipping 3rd element:

{ 1, 2, 4, 5 }

I can see even when running parallelly, stream consistently returns the last 3 elements though their order is different. So, stream can knows the index of each or is this a random coincidence?

Stream.of(1,2,3,4,5)
    .parallel()
    .skip(2)
    .forEach(System.out::println);

So my question is, is it possible to skip only one element from a list withing Java Streams?

like image 687
s1n7ax Avatar asked Jul 14 '26 16:07

s1n7ax


1 Answers

A Stream is not a data structure and doesn’t hold the data. It represent a pipeline through which data will flow and which functions to operate on the data. Especially you cannot point to a location in the stream where a certain element exists. What you could do is stream over the indices, filter out the index which you don't need and map to the list elements:

int n = 3;
List<Integer> myList = List.of(1, 2, 3, 4, 5);
IntStream.range(0, myList.size())
         .filter(i -> i !=n)
         .map(myList::get)
         .forEach(System.out::println);

or include only elements you need from the source when streaming:

Stream.concat(myList.subList(0, n).stream(), myList.subList(n+1, myList.size()).stream())
          .forEach(System.out::println);
like image 136
Eritrean Avatar answered Jul 17 '26 18:07

Eritrean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!