1

Is there any way to exclude last n elements from processing? Something similar to skip method but skipping from last.

Azodious
  • 13,752
  • 1
  • 36
  • 71

3 Answers3

6

You can achieve that with limit, provided you know the length in advance. Otherwise, you can't.

int lastToSkip = 5;

someList.stream()
    .limit(someList.size() - lastToSkip)
    .forEach(System.out::println);

As mentioned in the comments, you are trying to skip the last N lines of a file. But how do you know which are the last N lines if you don't know how many lines there are in total?

Some potential solutions:

  • Use a filter to make the trailer lines exempt. Maybe the lines of the trailer follow some pattern that the other lines do not, and you can apply a predicate to identify them, regardless of how many there are.

  • Do a first pass of the file to only count the lines. Do your processing in a second pass. Requires reading the whole file twice.

  • Use a backtracking approach. Apply your processing to the trailer lines as well, and after you have finished all lines then apply an inverse operation to effectively "undo" the impact of having processed the trailer lines. May not be possible depending on what your processing involes.

Michael
  • 41,989
  • 11
  • 82
  • 128
1

Maybe takeWhile​(Predicate<? super T> predicate) can help you. Available starting from Java 9.

IKo
  • 4,998
  • 8
  • 34
  • 54
0

There is no special method to exclude last n elements, because the stream potentially can be infinite, but you can skip first n elements and then limit the number of subsequent elements to process.

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

Or you can use filter, but only for sorted streams, to be sure that you get required elements.

Stream.of(1,2,3,4,5,0).filter(i -> i > 3).forEach(System.out::println); // 4 5