Home > Software design >  How to skip only nth element in java stream
How to skip only nth element in java stream

Time:01-26

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?

CodePudding user response:

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);
  • Related