首页  

Scala 实用代码     所属分类 scala 浏览量 692
val a = Seq(1,2)
for(item <- a) println(item)

val map = new java.util.concurrent.ConcurrentHashMap[String,Int]()
map.put("a",1)
map.put("b",2)

def getValue(key: String): Option[Int] = {
   Option(key).flatMap(key => Option(map.get(key)))
}

getValue(null)
getValue("a")
getValue("c")



val list = List(1,2,3)
list.map{ 
case 1 => "a" 
case _ => "b"
}


val list = List(1,2)
// List[String] = List(a, a)
list.map(item => "a")
list.map(_ => "a")



for(i <- 0 to 10  if i%2==0) yield i
for(i <- 0 to 10  if i%2==0) yield i*i

for{
 i <- 0 to 10 
 if i%2==0
} yield i


一行九九乘法表
(1 to 9).map{ 
    r => (1 to r).map{ c => f"$c×$r=${r*c}%-2d" }.mkString(" ") 
}.mkString("\n")


在一个长整型列表中寻找最大值,并返回这个最大值以及它所在的位置
def max(list: List[Long]): (Long, Int) = list.zipWithIndex.sorted.reverse.head
val list:List[Long] = List(3,7,2)
max(list)
res59: (Long, Int) = (7,1)


val func = {
  str:String => num:Int => 
  str+" "+num 
}
func: String => (Int => String) = $Lambda$1207/1538046991@3d458cb8
func("hello")(9)


def add(x: Int)(y: Int): Int = x + y
柯里化函数类型
Int => Int => Int
柯里化函数的类型声明是右结合的 
Int => (Int => Int)
入参是一个 Int ,返回是一个函数,返回函数入参 Int 返回类型 Int

def runAdd(func: Int => Int => Int)(x:Int)(y:Int) = func(x)(y)
runAdd(add)(1)(2)

scala.math.ceil(3.14)
scala.math.floor(3.14)
def run(f: (Double) => Double)  = f(1.5)
run(scala.math.ceil)
run(scala.math.floor)



九九乘法表
for(i <- 1 until 10 ;j <- 1 until 10){
  if(i>=j) print(i + "*" + j + "="+ i*j + "	")
  if(i==j) println() 
}



val doublevalue = 0.3d
val str = "hello"
println(s"str=$str , doublevalue=$doublevalue")
// str=hello , doublevalue=0.300
println(f"str=$str , doublevalue=$doublevalue%2.3f")




1 to 5 same 
1 until 6
1 to 10 by 2

返回值自动推断
val add = (a:Int,b:Int) => {
println(a+","+b)
a+b
}
add(1,2)




object  Hello extends App{
  println("hello")
}

Hello.main(null)

val list = List(1, 2, 3)
for(i <- list){
    println(i)
}

val map = Map(("a", 1), ("b", 2))
for((k, v) <- map){
  println(k + ": " + v)
}

Option 表示一个值是否存在,避免 NullPointerException
有两个子类 Some和None Some 表示值存在,None 表示值不存在

val opt: Option[String] = Some("hello")
//判断是否为None
opt.isEmpty // false
//如果为None,则返回默认值"default",否则返回值
opt.getOrElse("default") 
//如果为None则返回"DEFAULT",否则将字符转为大写
opt.fold("DEFAULT"){ value => value.toUpperCase } // "HELLO"
//功能同上
opt match {
  case Some(v) => v.toUpperCase
  case None => "DEFAULT"
}


List(1, 2, 3).map((i: Int) => { i + 1 }) 
List(1, 2, 3).map(i => i + 1 )
List(1, 2, 3).map(_ + 1 ) 
List(1, 2, 3).map(i => i.toString * i) // List(1, 22, 333)
List(1, 2, 3).flatMap(i => List(i, i)) // List(1, 1, 2, 2, 3, 3)

读取文件所有行 去重  按首字符排序,首字符相同按长度排序 打印结果
io.Source.fromFile("myfile.txt", "UTF-8").getLines().toList.distinct.sortBy(s => (s.charAt(0), s.length)).foreach(println)




(1 to 9).filter( _ % 2 == 0 )
(1 to 9).reduceLeft(_ + _)

val list = List(1,2,3,4,5)
list.reduceLeft(_-_)
-13

1-2-3-4-5 = -13


list.reduceRight(_-_)
3

1-(2-((3-(4-5)))) = 3

List("a", "b", "c", "a").groupBy(w => w).mapValues(_.length)
scala.collection.immutable.Map[String,Int] = Map(a -> 2, b -> 1, c -> 1)

首字母大写
List("hello", "scala").map(_.capitalize)
List[String] = List(Hello, Scala)

(1 to 3).mkString("(", ",", ")")

List(1,2,3).min 
List(1,2,3).max 
List(1,2,3).sum 

获取序列中最大的前3个数值和位置
List(1,2,3,4,5,6,7).zipWithIndex.sorted.reverse.take(3)
List[(Int, Int)] = List((7,6), (6,5), (5,4))


val fileContent = io.Source.fromFile("myfile.txt").mkString
val fileLines = io.Source.fromFile("myfile.txt").getLines.toList

获取当前工作目录
new java.io.File(".").getCanonicalPath()
 
并行计算
(1 to 99).par.sum

加权求和
val dataList = List(1,2,3)
val weightList = List(0.2,0.3,0.5)
dataList.zip(weightList).map{t => t._1 * t._2}.sum

按多个字段排序List
先按学生的年龄排序,如果年龄相同,则按分数排序

case class Student(name: String, age: Int, score: Int)
List(
      Student("a", 14, 60), 
      Student("b", 15, 80), 
      Student("a", 15, 70)
).sortBy(s => (s.age, s.score))
    
将List相邻元素分组
每相邻的10个元素分成一组
val list = (0 to 20).map(_.toString)
list.zipWithIndex.map(t => t._1 -> ((t._2 / 10) * 10)).groupBy(_._2).toList.sortBy(_._1).map(_._2.map(_._1))


取序列的第1个元素 包含判空逻辑
List(1, 2, 3).headOption.getOrElse(0)
List().headOption.getOrElse(0)
Nil.headOption.getOrElse(0) 




val arr = Array("a","b")
arr.foreach(print)


def echo(args: String*) = for (arg <- args) println(arg)
echo("a","b")


def max(x: Int, y: Int) = if (x > y) x else y

object Hi{
  def main(args: Array[String]) = println("Hello world!")
}

    val url:String = "http://codefun007.xyz/pv.htm"
    val source = Source.fromURL(url,"UTF-8")
    val result = source.mkString
    println(result)

    val str = "(hello,java)";
    val arr:Array[String] = str.stripPrefix("(").stripSuffix(")").split(",")
    println(arr)
    println(arr.mkString(","))

    arr.foreach(item=>println(item))
    arr.foreach(println(_))

    val str1 = (1 to 3).mkString("(", ",", ")")
    // (1,2,3)
    println(str1)
    val str2 = (1 until 3).mkString("(", ",", ")")
    // (1,2)
    println(str2)
    println("hello"*3)
    "hello".foreach(print(_))
    // "hello".foreach(println(_))
    println()
    "hello".getBytes().foreach(println(_))
    
    

https://gitee.com/dyyx/hellocode/blob/master/demo/scala/scalademo/src/main/java/demo/CodeDemo.scala
Scala 下划线的用途

上一篇     下一篇
akka http rest api demo

c语言 hello world 高逼格版本

IDEA 源码阅读技巧

IntelliJ IDEA 介绍

MAC 安装 wget

minio搭建