Is it possible to get next element in the Stream?

后端 未结 4 571
时光说笑
时光说笑 2020-12-06 00:08

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

4条回答
  •  感情败类
    2020-12-06 00:45

    Not exactly a Java solution, but possible to get next element in Kotlin with zip functions. Here is what I came up with functions. Looks much cleaner

    enum class RomanNumeral(private val value: Int) {
        I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
    
        operator fun minus(other: RomanNumeral): Int = value - other.value
    
        operator fun plus(num: Int): Int = num + value
    
        companion object {
            fun toRoman(ch: Char): RomanNumeral = valueOf(ch.toString())
        }
    }
    
    fun toNumber(roman: String): Int {
        return roman.map { RomanNumeral.toRoman(it) }
            .zipWithNext()
            .foldIndexed(0) { i, currentVal, (num1, num2) ->
                when {
                    num1 < num2            -> num2 - num1 + currentVal
                    i == roman.length - 2  -> num1 + (num2 + currentVal)
                    else                   -> num1 + currentVal
                }
            }
    }
    

提交回复
热议问题