Scala Collections – ListMap ”; Previous Next Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements. Declaring ListMap Variables The following is the syntax for declaring an ListMap variable. Syntax val colors = ListMap(“red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F”) Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following − Command var myMap1: ListMap[Char, Int] = colors + (“black” -> “#000000”); Processing ListMap Below is an example program of showing how to create, initialize and process ListMap − Example import scala.collection.immutable.ListMap object Demo { def main(args: Array[String]) = { var myMap: ListMap[String,String] = ListMap( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ); // Add an element var myMap1: ListMap[String,String] = myMap + (“white” -> “#FFFFFF”); // Print key values myMap.keys.foreach{ i => print( “Key = ” + i ) println(” Value = ” + myMap(i) ) } if( myMap.contains( “red” )) { println(“Red key exists with value :” + myMap(“red”)) } else { println(“Red key does not exist”) } if( myMap.contains( “maroon” )) { println(“Maroon key exists with value :” + myMap(“maroon”)) } else { println(“Maroon key does not exist”) } //removing element var myMap2: ListMap[String,String] = myMap – (“white”); // Create empty map var myMap3: ListMap[String,String] = ListMap.empty[String, String]; println(myMap1); println(myMap2); println(myMap3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Key = red Value = #FF0000 Key = azure Value = #F0FFFF Key = peru Value = #CD853F Red key exists with value :#FF0000 Maroon key does not exist ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF) ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F) ListMap() Print Page Previous Next Advertisements ”;
Category: scala Collections
Scala Collections – ListSet
Scala Collections – ListSet ”; Previous Next Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. ListSet implements immutable sets and uses list structure. Elements insertion order is preserved while storing the elements. Declaring ListSet Variables The following is the syntax for declaring an ListSet variable. Syntax var z : ListSet[String] = ListSet(“Zara”,”Nuha”,”Ayan”) Here, z is declared as an list-set of Strings which has three members. Values can be added by using commands like the following − Command var myList1: ListSet[String] = myList + “Naira”; Processing ListSet Below is an example program of showing how to create, initialize and process ListSet − Example import scala.collection.immutable.ListSet object Demo { def main(args: Array[String]) = { var myList: ListSet[String] = ListSet(“Zara”,”Nuha”,”Ayan”); // Add an element var myList1: ListSet[String] = myList + “Naira”; // Remove an element var myList2: ListSet[String] = myList – “Nuha”; // Create empty set var myList3: ListSet[String] = ListSet.empty[String]; println(myList); println(myList1); println(myList2); println(myList3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output ListSet(Zara, Nuha, Ayan) ListSet(Zara, Nuha, Ayan, Naira) ListSet(Zara, Ayan) ListSet() Print Page Previous Next Advertisements ”;
Scala Collections – Quick Guide ”; Previous Next Scala Collections – Overview Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items. For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones. This chapter throws light on the most commonly used collection types and most frequently used operations over those collections. Sr.No Collections with Description 1 Scala Lists Scala”s List[T] is a linked list of type T. 2 Scala Sets A set is a collection of pairwise different elements of the same type. 3 Scala Maps A Map is a collection of key/value pairs. Any value can be retrieved based on its key. 4 Scala Tuples Unlike an array or list, a tuple can hold objects with different types. 5 Scala Options Option[T] provides a container for zero or one element of a given type. 6 Scala Iterators An iterator is not a collection, but rather a way to access the elements of a collection one by one. Scala Collections – Environment Setup Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java -version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java -version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.8.0_31 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.8.0_31bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ”scala-2.13.1-installer.jar”. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java -jar scala-2.13.1-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java -jar scala-2.13.1-installer.jar Output − Welcome to the installation of Scala 2.13.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the following − Platform Command Output Windows >scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc. Linux $scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc.tut
Scala Collections – flatMap
Scala Collections – FlatMap Method ”; Previous Next flatMap() method is method of TraversableLike trait, it takes a predicate, applies it to each element of the collection and returns a new collection of elements returned by the predicate. Syntax The following is the syntax of flatMap method. def flatMap[B](f: (A) ? GenTraversableOnce[B]): TraversableOnce[B] Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition. Usage Below is an example program of showing how to use flatMap method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 5, 10) //apply operation val result = list.flatMap{x => List(x,x+1)} //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List(1, 2, 5, 6, 10, 11) Print Page Previous Next Advertisements ”;
Scala Collections – Option
Scala Collections – Option ”; Previous Next Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala”s Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map. Option type is used frequently in Scala programs and you can compare this with the null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or null if no value was found. Let”s say we have a method that retrieves a record from the database based on a primary key. def findPerson(key: Int): Option[Person] The method will return Some[Person] if the record is found but None if the record is not found. Let us follow the following program. Example object Demo { def main(args: Array[String]) { val capitals = Map(“France” -> “Paris”, “Japan” -> “Tokyo”) println(“capitals.get( “France” ) : ” + capitals.get( “France” )) println(“capitals.get( “India” ) : ” + capitals.get( “India” )) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output capitals.get( “France” ) : Some(Paris) capitals.get( “India” ) : None The most common way to take optional values apart is through a pattern match. For example try the following program. Example object Demo { def main(args: Array[String]) { val capitals = Map(“France” -> “Paris”, “Japan” -> “Tokyo”) println(“show(capitals.get( “Japan”)) : ” + show(capitals.get( “Japan”)) ) println(“show(capitals.get( “India”)) : ” + show(capitals.get( “India”)) ) } def show(x: Option[String]) = x match { case Some(s) => s case None => “?” } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output show(capitals.get( “Japan”)) : Tokyo show(capitals.get( “India”)) : ? Using getOrElse() Method Following is the example program to show how to use getOrElse() method to access a value or a default when no value is present. Example object Demo { def main(args: Array[String]) { val a:Option[Int] = Some(5) val b:Option[Int] = None println(“a.getOrElse(0): ” + a.getOrElse(0) ) println(“b.getOrElse(10): ” + b.getOrElse(10) ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output a.getOrElse(0): 5 b.getOrElse(10): 10 Using isEmpty() Method Following is the example program to show how to use isEmpty() method to check if the option is None or not. Example object Demo { def main(args: Array[String]) { val a:Option[Int] = Some(5) val b:Option[Int] = None println(“a.isEmpty: ” + a.isEmpty ) println(“b.isEmpty: ” + b.isEmpty ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Example a.isEmpty: false b.isEmpty: true Print Page Previous Next Advertisements ”;
Scala Collections – HashMap
Scala Collections – HashMap ”; Previous Next Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same. Declaring HashMap Variables The following is the syntax for declaring an HashMap variable. Syntax val colors = HashMap(“red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F”) Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following − Command var myMap1: HashMap[Char, Int] = colors + (“black” -> “#000000”); Processing HashMap Below is an example program of showing how to create, initialize and process HashMap − Example import scala.collection.immutable.HashMap object Demo { def main(args: Array[String]) = { var myMap: HashMap[String,String] = HashMap( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ); // Add an element var myMap1: HashMap[String,String] = myMap + (“white” -> “#FFFFFF”); // Print key values myMap.keys.foreach{ i => print( “Key = ” + i ) println(” Value = ” + myMap(i) ) } if( myMap.contains( “red” )) { println(“Red key exists with value :” + myMap(“red”)) } else { println(“Red key does not exist”) } if( myMap.contains( “maroon” )) { println(“Maroon key exists with value :” + myMap(“maroon”)) } else { println(“Maroon key does not exist”) } //removing element var myMap2: HashMap[String,String] = myMap – (“white”); // Create empty map var myMap3: HashMap[String,String] = HashMap.empty[String, String]; println(myMap1); println(myMap2); println(myMap3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Key = azure Value = #F0FFFF Key = peru Value = #CD853F Key = red Value = #FF0000 Red key exists with value :#FF0000 Maroon key does not exist HashMap(azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF, red -> #FF0000) HashMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000) HashMap() Print Page Previous Next Advertisements ”;
Discuss Scala Collections ”; Previous Next Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Print Page Previous Next Advertisements ”;
Scala Collections – TreeSet
Scala Collections – TreeSet ”; Previous Next Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. TreeSet implements immutable sets and keeps elements in sorted order. Declaring TreeSet Variables The following is the syntax for declaring an TreeSet variable. Syntax var z : TreeSet[String] = TreeSet(“Zara”,”Nuha”,”Ayan”) Here, z is declared as an tree-set of Strings which has three members. Values can be added by using commands like the following − Command var myList1: TreeSet[String] = myList + “Naira”; Processing TreeSet Below is an example program of showing how to create, initialize and process TreeSet − Example import scala.collection.immutable.TreeSet object Demo { def main(args: Array[String]) = { var mySet: TreeSet[String] = TreeSet(“Zara”,”Nuha”,”Ayan”); // Add an element var mySet1: TreeSet[String] = mySet + “Naira”; // Remove an element var mySet2: TreeSet[String] = mySet – “Nuha”; // Create empty set var mySet3: TreeSet[String] = TreeSet.empty[String]; println(mySet); println(mySet1); println(mySet2); println(mySet3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output TreeSet(Ayan, Nuha, Zara) TreeSet(Ayan, Naira, Nuha, Zara) TreeSet(Ayan, Zara) TreeSet() Print Page Previous Next Advertisements ”;
Scala Collections – zip
Scala Collections – Zip Method ”; Previous Next zip() method is a member of IterableLike trait, it is used to merge a collection to current collection and result is a collection of pair of tuple elements from both collections. Syntax The following is the syntax of zip method. def zip[B](that: GenIterable[B]): Iterable[(A, B)] Here, zip method takes a collection as parameter. This method returns the updated collection of pair as result. Usage Below is an example program of showing how to use zip method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3 ,4) val list1 = List(“A”, “B”, “C”, “D”) //apply operation to create a zip of list val list2 = list zip list1 //print list println(list2) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output List((1,A), (2,B), (3,C), (4,D)) Print Page Previous Next Advertisements ”;
Scala Collections – HashSet
Scala Collections – HashSet ”; Previous Next Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved. Declaring HashSet Variables The following is the syntax for declaring an HashSet variable. Syntax var z : HashSet[String] = HashSet(“Zara”,”Nuha”,”Ayan”) Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following − Command var myList1: HashSet[String] = myList + “Naira”; Processing HashSet Below is an example program of showing how to create, initialize and process HashSet − Example import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { var mySet: HashSet[String] = HashSet(“Zara”,”Nuha”,”Ayan”); // Add an element var mySet1: HashSet[String] = mySet + “Naira”; // Remove an element var mySet2: HashSet[String] = mySet – “Nuha”; // Create empty set var mySet3: HashSet[String] = HashSet.empty[String]; println(mySet); println(mySet1); println(mySet2); println(mySet3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output HashSet(Zara, Nuha, Ayan) HashSet(Zara, Nuha, Ayan, Naira) HashSet(Zara, Ayan) HashSet() Print Page Previous Next Advertisements ”;