Java – can I get the next element in the stream?

I'm trying to convert the for loop to function code I need to look forward to a value, or I can look at a value Can I use streaming?

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();
        }

    }

}

Solution

No, it's impossible to use streams, at least not easy Stream API abstracts from the order of processing elements: streams can be processed in parallel or in reverse order Therefore, there are no "next element" and "previous element" in the stream abstraction

You should use the API that best suits the job: if you need to apply some operations to all elements of the collection and you are not interested in the order, the flow is good If you need to process elements in a certain order, you must use iterators or access list elements through indexes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
***
下一篇>>