Pacific-Design.com

    
Home Index

1. Scala

2. Collections

Scala / Collections /

Collection - Monad

Most Scala collections are monadic, and operating on them using map and flatMap operations, or using for-comprehensions is referred to as monadic-style. People will often refer to the monadic nature of a collection (or other container) using the word monad, eg. the List MONAD.

Scala Standard Library - Collections

Scala - List, Seq, Set, ListBuffer


package kduraj

import java.io.File
import scala.collection.mutable.ListBuffer
import scala.io.Source

/**
 * Basic List, Set, Seq
 */
class BasicList(file: File) {

  /**
   * List - has duplicates
   */
  def read2List(): Unit = {

    var list1 = List[String]()
    var list2 = List[String]()

    Source.fromFile(file).getLines.foreach { line =>
      val col = line.split(",").map(_.trim)
      list1 = list1 :+ col(0) // adds to end of the list
      list2 ::= col(0) // adds to beginning of the list
    }
    println("InOrder : " + list1.toString())
    println("Reverse : " + list2.toString())

  }

  /**
   * Sequence - has duplicates, linear time
   */
  def read2Seq(): Unit = {

    var seq = Seq[String]()
    Source.fromFile(file).getLines.foreach { line =>
      val col = line.split(",").map(_.trim)
      seq = seq :+ col(0)
    }
    println("Sequence: " + seq.toString())

  }

  /**
   * Set - has no duplicates, linear time
   */
  def read2Set(): Unit = {

    var set = Set[String]()

    Source.fromFile(file).getLines.foreach { line =>
      val col = line.split(",").map(_.trim)
      set += col(0)
    }

    println(set.toString())
  }

  /**
   * ListBuffer - constant time
   */
  def read2ListBuffer(): Unit = {

    val buffer1 = ListBuffer[String]()
    val buffer2 = ListBuffer[String]()

    Source.fromFile(file).getLines.foreach { line =>
      val col = line.split(",").map(_.trim)
      buffer1.append(col(0)) // append to buffer
      buffer2.prepend(col(0)) // prepend to buffer
    }
    println("ListBuffer Append  : " + buffer1.toString())
    println("ListBuffer Prepend : " + buffer2.toString())

  }

}

Scala - Map, HashMap, ListMap, TreeMap


package kduraj

import java.io.File
import scala.collection.mutable
import scala.collection.immutable.TreeMap
import scala.io.Source

/**
 * Reading data into Map, HashMap, ListMap, TreeMap
 */
class BasicMaps(file: File) {

  /**
   * Map mutable
   */
  def read2Map(): Unit = {

    val map = mutable.Map[String, Int]()

    Source.fromFile(file).getLines.foreach { line =>
        val col = line.split(",").map(_.trim)

        if (map.getOrElse(col(0), null) == null) {
          map += (col(0) -> col(1).toInt)
        } else { //incrementing duplicate key values
          map.update(col(0), map(col(0)) + 1 )
        }
    }

    println("Map: " + map.toString())
  }

  /**
   * HashMap mutable
   */
  def read2HashMap(): Unit = {

    val hash = mutable.HashMap[String, Int]()

    Source.fromFile(file).getLines.foreach { line =>
        val col = line.split(",").map(_.trim)

        if (hash.getOrElse(col(0), null) == null) {
          hash += (col(0) -> col(1).toInt)
        } else { //incrementing duplicate key values
          hash.update(col(0), hash(col(0)) + 1 )
        }
    }

    println("HashMap: " + hash.toString())
  }

  /**
   * ListMap mutable
   */
  def read2ListMap(): Unit = {

    val list = mutable.ListMap[String, Int]()

    Source.fromFile(file).getLines.foreach { line =>
        val col = line.split(",").map(_.trim)

        if (list.getOrElse(col(0), null) == null) {
          list += (col(0) -> col(1).toInt)
        } else { //incrementing duplicate key values
          list.update(col(0), list(col(0)) + 1 )
        }
    }

    println("ListMap: " + list.toString())
  }

  /**
   * TreeMap immutable
   */
  def read2TreeMap(): Unit = {

    var tree = TreeMap[String, Int]()

    Source.fromFile(file).getLines.foreach { line =>
        val col = line.split(",").map(_.trim)

        if (tree.getOrElse(col(0), null) == null) {
          tree += (col(0) -> col(1).toInt)
        } else { //incrementing duplicate key values
          val i = tree(col(0)) + 1
          tree += (col(0) -> i)
        }
    }

    println("TreeMap: " + tree.toString())
  }

}

Main App


package kduraj

import java.io.File

object App extends App {

  val file = new File(getClass.getClassLoader.getResource("test.dat").getPath)
  var count: Int = 0

  println("-------- Lists ------------")
  testLists
  println("--------- Maps ------------")
  testMaps

  def testLists: Unit = {
    val list = new BasicList(file)
    list.read2List()
    list.read2Seq()
    list.read2Set()
    list.read2ListBuffer()
  }


  def testMaps: Unit = {
    val map = new BasicMaps(file)
    map.read2Map()
    map.read2HashMap()
    map.read2ListMap()
    map.read2TreeMap()
  }

}

Input

barbara, 22
kevin, 60
zen, 35
alfa, 10
zen, 55
kevin, 45

Output

-------- Lists ------------
InOrder : List(barbara, kevin, zen, alfa, zen, kevin)
Reverse : List(kevin, zen, alfa, zen, kevin, barbara)
Sequence: List(barbara, kevin, zen, alfa, zen, kevin)
Set(barbara, kevin, zen, alfa)
ListBuffer Append  : ListBuffer(barbara, kevin, zen, alfa, zen, kevin)
ListBuffer Prepend : ListBuffer(kevin, zen, alfa, zen, kevin, barbara)

--------- Maps ------------
Map: Map(alfa -> 10, kevin -> 61, zen -> 36, barbara -> 22)
HashMap: Map(alfa -> 10, kevin -> 61, zen -> 36, barbara -> 22)
ListMap: Map(kevin -> 61, barbara -> 22, zen -> 36, alfa -> 10)
TreeMap: Map(alfa -> 10, barbara -> 22, kevin -> 61, zen -> 36)