是否可以在 Stream 中获取下一个元素? [英] Is it possible to get next element in the Stream?

查看:20
本文介绍了是否可以在 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 中获取下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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