Skip to content

Instantly share code, notes, and snippets.

@rupeshtr78
Created October 30, 2020 17:22
Show Gist options
  • Save rupeshtr78/bb3e4a223f7279a3c529784440e2c123 to your computer and use it in GitHub Desktop.
Save rupeshtr78/bb3e4a223f7279a3c529784440e2c123 to your computer and use it in GitHub Desktop.
package scalacollections
object ScalaCollectionsMap {
import scala.collection.immutable.{HashMap, ListMap}
val res: Seq[Char] = "hello world".toList.filter(_.isLetter).map(_.toUpper) //List(H, E, L, L, O, W, O, R, L, D)
val resMap: Map[Char, Seq[Char]] = res.groupBy(x => x) //Map(E -> List(E), L -> List(L, L, L), H -> List(H), W -> List(W), R -> List(R), O -> List(O, O), D -> List(D))
val res3: Map[Char, Int] = resMap.map(l => (l._1,l._2.size)) //Map(E -> 1, L -> 3, H -> 1, W -> 1, R -> 1, O -> 2, D -> 1)
//foldLeft
val aSet = Set("RTR","Reva", "Rhea")
val aMap = Map("RTR" -> Set("Roopa"))
val aSetFoldLeft = aSet.foldLeft(Map[String,Set[String]]())((B,A) => B + (A -> aSet.filter(x => x != A)))
val aSetFoldLeft2 = aSet.foldLeft(aMap)((B,A) => B + (A -> aSet))
// aSetFoldLeft = Map(RTR -> Set(Reva, Rhea), Reva -> Set(RTR, Rhea), Rhea -> Set(RTR, Reva))
// aSetFoldLeft2 = Map(RTR -> Set(RTR, Reva, Rhea), Reva -> Set(RTR, Reva, Rhea), Rhea -> Set(RTR, Reva, Rhea))
val aMap1 = Map('l' -> 1, 'a' -> 2,'c' -> 1, 's' -> 2)
val result01 = aMap1('s')
//Pattern Match
val aMapPattern = aMap1.map(pair => pair match { // Map(l -> 1, a -> 2, c -> 1, s -> 3)
case (key , value ) if(key =='s') => (key , value +1)
case _ => pair
})
//Transform
val aListMapValues = aMap1.transform((k, v) => {
if (k == 's') v + 1
else v
})
//mapValues
aListMapValues.mapValues(value => if(value ==1) 0 else value)
//Maps → Associate key to value
val emptyMap: Map[String,Int] = Map() // Empty Map
val phoneNum = Map(("Rupesh",313),("Roopa",284)) // Map(Rupesh -> 313, Roopa -> 284)
val phoneArrow = Map("Rupesh" -> 313,"Roopa"-> 284) // Map(Rupesh -> 313, Roopa -> 284)
//Access Values
phoneNum.contains("Roopa") // true
phoneNum("Rupesh") // 313
//withDefaultValue // if key does not exist it will crash apply
val phoneWDefault = Map("Rupesh" -> 313,"Roopa"-> 284).withDefaultValue(-100)
phoneWDefault("Rhea") // -100
//Add Remove a pairing
val rheaNum = "Rhea" -> 832
val newPhoneBook = phoneWDefault + rheaNum //Map(Rupesh -> 313, Roopa -> 284, Rhea -> 832)
var removeElement = newPhoneBook - ("Rhea") // Map(Rupesh -> 313, Roopa -> 284)
val resultTake = newPhoneBook.take(2) //Map(Rupesh -> 313, Roopa -> 284)
//Functionals on maps
// map, flatMap, filter
val mapMap1 = phoneNum.map(pair => pair._1.toLowerCase -> pair._2)
//map → duplicate keys should be avoided
val mapMap2 = newPhoneBook.map(pair => pair._1.toUpperCase() -> pair._2)
//filterKeys
newPhoneBook.filterKeys(x => x.startsWith("Rh")) //Map(Rhea -> 832)
//filter
newPhoneBook.filter(x => x._1 =="Rupesh") // Map(Rupesh -> 313)
//mapValues
newPhoneBook.mapValues(v => "001-" + v) // Map(Rupesh -> 001-313, Roopa -> 001-284, Rhea -> 001-832) changes only values
//Conversions
newPhoneBook.toList // List((Rupesh,313), (Roopa,284), (Rhea,832))
List(("Reva",832)).toMap // Map(Reva -> 832) List to Map
//groupBy
val familyList = List("Rupesh", "Roopa","Ammu","Achu")
val fam = familyList.groupBy(x => x.charAt(0)) // Map(A -> List(Ammu, Achu), R -> List(Rupesh, Roopa)) groupBy first Letter
//maxBy
val familyList2 = List("Rupesh", "Roopa","Ammu","Achu","Amy","Annie")
// maxBy the size of the list
val nChar = familyList2.groupBy(x => x.charAt(0)) // Map(A -> List(Ammu, Achu, Amy, Annie), R -> List(Rupesh, Roopa))
val mxChar = nChar.maxBy(pair => pair._2.size) // (A,List(Ammu, Achu, Amy, Annie))
//Count
nChar.count(pair => pair._2.size >2)
//Change Existing Values
val aMap2 = Map('l' -> 1, 'a' -> 2,'c' -> 1, 's' -> 2)
//Add to Map
val addValue = aMap2 + ('m' -> 4)
val changeValue = aMap2 + ('s' -> 4)
//Remove Key
val aMap3 = Map('l' -> 1, 'a' -> 2, 'c' -> 1, 's' -> 2)
val removeKey = aMap3 - ('s')
//Contains → Tests whether this map contains a binding for a key.
val aMap4 = Map('l' -> 1, 'a' -> 2,'c' -> 1, 's' -> 2)
val result = aMap4.contains('s') //true
//For Loop → Map
val myString = "Scala Scala Scala Scala"
def countCharacter(myString:String):Map[Char,Int] = {
val strListArr = myString.toLowerCase.toCharArray.sorted
val uniqueChar = strListArr.toSet
(for (i <- uniqueChar) yield (i ,strListArr.count(x => x== i))).toMap
}
//Values contains
val result2 = phoneNum.values.count(x=> x ==313)
//Collects all keys of this map in a set.Return a set containing all keys of this map. Not values.
val keySet = phoneNum.keySet // Set(Bob, Alice, Mary, David, Charlie)
// HashMap is used to store element.
// It use hash code to store elements and return a map.
var hashMap = HashMap("A"->"Apple","B"->"Ball","C"->"Cat")
hashMap.foreach {
case (key, value) => println (key + " -> " + value) } // Iterating elements
println(hashMap("B")) // Accessing value by using key Ball
var newHashMap = hashMap+("D"->"Doll") // Map(A -> Apple, B -> Ball, C -> Cat, D -> Doll)
//ListMap
// This class implements immutable maps by using a list-based data structure.
// It maintains insertion order and returns ListMap. This collection is suitable for small elements.
// You can create empty ListMap either by calling its constructor or using ListMap.empty method.
var listMap = ListMap("Rice"->"100","Wheat"->"50","Gram"->"500") // ListMap(Rice -> 100, Wheat -> 50, Gram -> 500)
listMap.foreach{
case(key,value)=>println(key+"->"+value)
}
println(listMap("Gram")) // 500
var newListMap = listMap+("Pulses"->"550")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment