I am trying to convert this Scala code to Groovy:
val r = BigInt(2).pow(1000).toString.view.map(_.asDigit).sum
What is the equivalent of "view" to groovy?
Java8 brings chars()
(basically an iterator), which you can reduce over for the sum:
groovy:000> 2G.pow(1000).toString().chars().reduce(0){ a,b -> a+b-48 }
===> 1366
Or closer to your Scala code (map, sum):
groovy:000> 2G.pow(1000).toString().chars().map{ it-48 }.sum()
===> 1366
That magic 48 is the ascii for "0".
As a generic answer: Many of the functional methods in groovy tend to realize the results, but Java 8 streams are just as easy to use from Groovy.
def result = new BigInteger(2).pow(1000).toString().toCharArray().toList().sum { it - 48 }
要么
def result1 = 2g.pow(1000).toString().toCharArray().toList().sum { it - 48 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.