Java 8 Stream:如何比较当前元素和下一个元素? [英] Java 8 Stream: How to compare current element with next element?

查看:108
本文介绍了Java 8 Stream:如何比较当前元素和下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java 8 Streams从 List 获取下一个元素?

How to get the next element from a List using Java 8 Streams?

如果要遍历 List ,我想将当前值与列表的下一个元素进行比较.

If I am iterating over a List, I want to compare current with next element of the list.

使用Java 8 Stream可以实现吗?

Is it doable using Java 8 Stream?

推荐答案

我免费的 StreamEx 库允许您处理使用其他 pairMap的流元素 中间操作.像这样:

My free StreamEx library allows you to process the pairs of the stream elements using additional pairMap intermediate operation. Like this:

StreamEx.of(input).pairMap((current, next) -> doSomethingWith(current, next));

其中 input Collection ,数组或 Stream .例如,通过这种方式,您可以轻松检查输入是否已排序:

Where input is a Collection, array or Stream. For example, this way you can easily check whether input is sorted:

boolean isSorted = StreamEx.of(input)
                           .pairMap((current, next) -> next.compareTo(current))
                           .allMatch(cmp -> cmp >= 0);

还有 forPairs 终端操作,它是对所有输入元素对的 forEach 模拟:

StreamEx.of(input).forPairs((current, next) -> doSomethingWith(current, next));

这些功能可以与任何流源(无论是否随机访问)很好地配合,并完全支持并行流.

These features work nicely with any stream source (either random access or not) and fully support the parallel streams.

这篇关于Java 8 Stream:如何比较当前元素和下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆