从流中跳过最后一个

huangapple go评论73阅读模式
英文:

Skipping from last in a stream

问题

有没有办法在处理时排除最后的n个元素?类似于skip方法,但是从最后开始跳过。

英文:

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

答案1

得分: 6

你可以使用 limit 来实现这一点,前提是你事先知道长度。否则,你就无法做到。

int lastToSkip = 5;

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

如评论中所述,你正在尝试跳过文件的最后 N 行。但如果你不知道总共有多少行,你又怎么知道哪些是最后的 N 行呢?

一些潜在的解决方案:

  • 使用 filter 来使尾随行免于处理。也许尾随行遵循其他行不遵循的某种模式,你可以应用谓词来识别它们,而不管有多少行。

  • 对文件进行第一次遍历以仅计算行数。在第二次遍历中进行处理。需要两次完全读取整个文件。

  • 使用回溯方法。在处理其他行之后,也对尾随行应用处理,然后在完成所有行之后应用反向操作,以有效地“撤消”对尾随行处理的影响。根据你的处理方式,可能不可行。

英文:

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.

答案2

得分: 1

takeWhile​(Predicate<? super T> predicate) 可能会对你有帮助。
从Java 9开始可用。

英文:

Maybe takeWhile​(Predicate&lt;? super T&gt; predicate) can help you.
Available starting from Java 9.

答案3

得分: 0

没有特殊的方法来排除最后的 n 个元素,因为流可能是无限的,但您可以先 跳过n 个元素,然后 限制 处理的后续元素数量。

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

或者您可以使用 filter,但只适用于已排序的流,以确保获取 所需的 元素。

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

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 -&gt; i &gt; 3).forEach(System.out::println); // 4 5

huangapple
  • 本文由 发表于 2020年8月10日 19:39:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63339440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定