簡體   English   中英

相當於Scala視圖的Groovy

[英]Groovy equivalent of Scala views

我正在嘗試將此Scala代碼轉換為Groovy:

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

groovy的“視圖”等同於什么?

Java8帶來了chars() (基本上是一個迭代器),您可以減少其總和:

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

或更接近您的Scala代碼(地圖,總和):

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

魔法48是“ 0”的數字。

作為一個通用的答案: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