Java,Pyhon,Scala比較(一)map,reduce

jclian91發表於2017-11-09

使用map,reduce函式,將字串陣列[‘1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’]轉化為數字123456789.

Java

import java.util.List;
import java.util.Arrays;
import java.util.stream.Stream;

public class strToInt {
    public static void main(String[] args) {
        List<String> lst = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9");
        System.out.println(lst.stream().map((x) -> Integer.valueOf(x)).reduce((x,y) -> 10*x+y));

    }
}

Python

from functools import reduce
lst = [`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`]
reduce(lambda x,y: 10*x+y,map(lambda x:int(x), lst))

scala

object mapReduce{
    def main(args:Array[String]){
        println(Array("1","2","3","4","5","6","7","8","9").map(_.toInt).reduce(_*10+_));
    }
}


相關文章