Is it possible to get next element in the Stream?(是否可以在 Stream 中获取下一个元素?)
问题描述
我正在尝试将 for 循环 转换为功能代码.我需要向前看一个值,也需要向后看一个值.可以使用流吗?以下代码是将罗马文本转换为数值.不确定带有两个/三个参数的 reduce 方法是否可以提供帮助.
I am trying to converting a for loop to functional code. I need to look ahead one value and also look behind one value. Is it possible using streams?
The following code is to convert the Roman text to numeric value.
Not sure if reduce method with two/three arguments can help here.
int previousCharValue = 0;
int total = 0;
for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
RomanNumeral romanNum = RomanNumeral.valueOf(Character.toString(current));
if (previousCharValue > 0) {
total += (romanNum.getNumericValue() - previousCharValue);
previousCharValue = 0;
} else {
if (i < input.length() - 1) {
char next = input.charAt(i + 1);
RomanNumeral nextNum = RomanNumeral.valueOf(Character.toString(next));
if (romanNum.getNumericValue() < nextNum.getNumericValue()) {
previousCharValue = romanNum.getNumericValue();
}
}
if (previousCharValue == 0) {
total += romanNum.getNumericValue();
}
}
}
推荐答案
不,使用流是不可能的,至少不容易.流 API 抽象出处理元素的顺序:流可以并行处理,也可以以相反的顺序处理.所以流抽象中不存在下一个元素"和上一个元素".
No, this is not possible using streams, at least not easily. The stream API abstracts away from the order in which the elements are processed: the stream might be processed in parallel, or in reverse order. So "the next element" and "previous element" do not exist in the stream abstraction.
您应该使用最适合该工作的 API:如果您需要对集合的 所有 元素应用一些操作并且您对顺序不感兴趣,那么流非常好.如果您需要按特定顺序处理元素,则必须使用迭代器或通过索引访问列表元素.
You should use the API best suited for the job: stream are excellent if you need to apply some operation to all elements of a collection and you are not interested in the order. If you need to process the elements in a certain order, you have to use iterators or maybe access the list elements through indices.
这篇关于是否可以在 Stream 中获取下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 Stream 中获取下一个元素?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
