Pacific-Design.com

    
Home Index

1. Scala

+ 1 Map Reduce

+ 2 Functions

+ 3a Regex

+ 3b Regex

+ 4 Loops Match

+ 5a HashMap

+ 5a List

+ 6 Option

+ Abstract

+ Akka

+ Bash Scala

+ Collections

+ Companion Objects

+ Date Computation

+ Files IO

+ Implicit Class

+ Nested Objects

+ User Input

+ Vim

Scala /

Read CSV File

object CSVDemo extends App {

  println("Month, Income, Expenses, Profit")
  val bufferedSource = io.Source.fromFile("/tmp/finance.csv")

  for (line <- bufferedSource.getLines) {

    val cols = line.split(",").map(_.trim)
    println(s"${cols(0)}|${cols(1)}|${cols(2)}|${cols(3)}")

  }

  bufferedSource.close

}

Create Hexadecimal Numbers

for (a <- 0 to 15; b <- 0 to 15; c <- 0 to 15) { 

    println( Integer.toHexString(a) 
           + Integer.toHexString(b) 
           + Integer.toHexString(c)) 

}

/*
Output

000
001
002
003
004
005
006
007
008
009
00a
00b
00c
*/

Group By ListBuffer

 def testListBufferGroupBy(): Unit = {

    var buffer = new ListBuffer[String]()

    deviceChannelPaths.foreach { keyVal =>
      val rec = keyVal._2
      buffer += rec

    }
    val list = buffer.toList
    val counts = list.groupBy(w => w).mapValues(_.size)

    println("testListBuffer")
    counts.foreach { keyVal => println(keyVal._2 + ":" + keyVal._1) }
  }

Trait

trait Animal {
  val greeting: Option[String]
  var age: Option[Int] = None
  override def toString = s"I say $greeting, and I'm $age years old."
}

class Dog extends Animal {
  val greeting = Some("Woof")
  age = Some(2)
}

object Test extends App {
  val d = new Dog
  println(d)
}

/*
I say Some(Woof), and I'm Some(2) years old.
*/

Scala Code Snippets

// Replace empty string(or null with a default string
scala> def q(i: Int) = s(i) match { case ""|null => "" case x => x }

// read split line of test and trim
val cols = line.split(",").map(_.trim)

// Parallel Programming with Scala
val stream: InputStream = getClass.getResourceAsStream("/src/main/resource/test.txt")
val vector: ParVector[String] = scala.io.Source.fromInputStream(stream).getLines.toVector.par

Scala Links