简体   繁体   English

相当于Scala视图的Groovy

[英]Groovy equivalent of Scala views

I am trying to convert this Scala code to Groovy: 我正在尝试将此Scala代码转换为Groovy:

val r = BigInt(2).pow(1000).toString.view.map(_.asDigit).sum

What is the equivalent of "view" to groovy? groovy的“视图”等同于什么?

Java8 brings chars() (basically an iterator), which you can reduce over for the sum: Java8带来了chars() (基本上是一个迭代器),您可以减少其总和:

groovy:000> 2G.pow(1000).toString().chars().reduce(0){ a,b -> a+b-48 }
===> 1366

Or closer to your Scala code (map, sum): 或更接近您的Scala代码(地图,总和):

groovy:000> 2G.pow(1000).toString().chars().map{ it-48 }.sum()
===> 1366

That magic 48 is the ascii for "0". 魔法48是“ 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. 作为一个通用的答案:Groovy中的许多功能方法都倾向于实现结果,但是从Groovy中使用Java 8流同样容易。

def result = new BigInteger(2).pow(1000).toString().toCharArray().toList().sum { it - 48 }

要么

def result1 = 2g.pow(1000).toString().toCharArray().toList().sum { it - 48 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM