Scala小代码

判断一个字符串是否是数字

scala> "12434".forall(i => Character.isDigit(i))
res0: Boolean = true 

字符串按字母顺序排序

scala> "HELLO".sorted
res1: String = EHLLO

or

scala> "HELLO".sortWith(_ < _)
res2: String = EHLLO

将集合中的所有元素拼接成字符串

scala> List("A","B","C","D").mkString(",")
res3: String = A,B,C,D

or

scala> List("A","B","C","D").mkString("<",",",">")
res4: String = <A,B,C,D>

将List[List[Int]] 变成 List[Int]

scala> List(List(1,2,3),List(4,5,6)).flatten
res5: List[Int] = List(1, 2, 3, 4, 5, 6)

打印乘法口诀表

scala> for(i <- 1 to 9;j <- 1 to i) print(s"$j * $i = ${j*i}${if(i == j) "\n" else "\t"}")

将List元素复制5遍

scala> (1 to 5).flatMap(x => List(1,2,3)).toList
res6: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

1到100之间奇数的平方的和

scala> (1 to 100 by 2).map(i=>i*i).sum
res5: Int = 166650

逆序for循环

scala>  for (i <- 11.to(1,-1))print(i+",")
res6:11,10,9,8,7,6,5,4,3,2,1,

转载于:https://my.oschina.net/xjpz/blog/704023

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值