Scala Collections – Find Method ”; Previous Next find() method is method used by Iterators to find an element which satisfies a given predicate. Syntax The following is the syntax of find method. def find(p: (A) => Boolean): Option[A] Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the iterator. 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 find method − Example object Demo { def main(args: Array[String]) = { val iterator = Iterator(3, 6, 9, 4, 2) //apply operation val result = iterator.find(x=>{x % 3 == 0}) //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 Some(3) Print Page Previous Next Advertisements ”;
Category: scala Collections
Scala Collections – DropWhile Method ”; Previous Next dropWhile() method is method used by List to drop all elements which satisfies a given condition. Syntax The following is the syntax of dropWhile method. def dropWhile(p: (A) => Boolean): List[A] Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list except dropped ones. Usage Below is an example program of showing how to use dropWhile method − Example object Demo { def main(args: Array[String]) = { val list = List(3, 6, 9, 4, 2) // print list println(list) //apply operation val result = list.dropWhile(x=>{x % 3 == 0}) //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(3, 6, 9, 4, 2) List(4, 2) Print Page Previous Next Advertisements ”;
Scala Collections – drop
Scala Collections – Drop Method ”; Previous Next drop() method is method used by List to select all elements except first n elements of the list. Syntax The following is the syntax of drop method. def drop(n: Int): List[A] Here, n is the number of elements to be dropped from the list. This method returns the all the elements of list except first n ones. Usage Below is an example program of showing how to use drop method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3, 4, 5) // print list println(list) //apply operation val result = list.drop(3) //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, 3, 4, 5) List(4, 5) Print Page Previous Next Advertisements ”;
Scala Collections – Map
Scala Collections – Map ”; 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. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can”t be changed. By default, Scala uses the immutable Map. If you want to use the mutable Map, you”ll have to import scala.collection.mutable.Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable.Map. The Following is the example statements to declare immutable Maps − // Empty hash table whose keys are strings and values are integers: var A:Map[Char,Int] = Map() // A map with keys and values. val colors = Map(“red” -> “#FF0000”, “azure” -> “#F0FFFF”) While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable. If we want to add a key-value pair to a Map, we can use the operator + as follows. A + = (”I” -> 1) A + = (”J” -> 5) A + = (”K” -> 10) A + = (”L” -> 100) Basic Operations on MAP All operations on maps can be expressed in terms of the following three methods. Sr.No Methods & Description 1 keys This method returns an iterable containing each key in the map. 2 values This method returns an iterable containing each value in the map. 3 isEmpty This method returns true if the map is empty otherwise false. Try the following example program showing usage of the Map methods. Example object Demo { def main(args: Array[String]) { val colors = Map( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ) val nums: Map[Int, Int] = Map() println( “Keys in colors : ” + colors.keys ) println( “Values in colors : ” + colors.values ) println( “Check if colors is empty : ” + colors.isEmpty ) println( “Check if nums is empty : ” + nums.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 Output Keys in colors : Set(red, azure, peru) Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F) Check if colors is empty : false Check if nums is empty : true Concatenating Maps You can use either ++ operator or Map.++() method to concatenate two or more Maps, but while adding Maps it will remove duplicate keys. Try the following example program to concatenate two Maps. Example object Demo { def main(args: Array[String]) { val colors1 = Map( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ) val colors2 = Map( “blue” -> “#0033FF”, “yellow” -> “#FFFF00”, “red” -> “#FF0000″ ) // use two or more Maps with ++ as operator var colors = colors1 ++ colors2 println( “colors1 ++ colors2 : ” + colors ) // use two maps with ++ as method colors = colors1.++(colors2) println( “colors1.++(colors2)) : ” + colors ) } } 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 colors1 ++ colors2 : Map(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000) colors1.++(colors2)) : Map(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000) Print Keys and Values from a Map You can iterate through the keys and values of a Map using “foreach” loop. Here, we used method foreach associated with iterator to walk through the keys. Following is the example program. Example object Demo { def main(args: Array[String]) { val colors = Map(“red” -> “#FF0000”, “azure” -> “#F0FFFF”,”peru” -> “#CD853F”) colors.keys.foreach{ i => print( “Key = ” + i ) println(” Value = ” + colors(i) ) } } } 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 Check for a key in Map You can use either Map.contains method to test if a given key exists in the map or not. Try the Following example program to key checking. Example object Demo { def main(args: Array[String]) { val colors = Map( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ) if( colors.contains( “red” )) { println(“Red key exists with value :” + colors(“red”)) } else { println(“Red key does not exist”) } if( colors.contains( “maroon” )) { println(“Maroon key exists with value :” + colors(“maroon”)) } else { println(“Maroon key does not exist”) } } } 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 Red key exists with value :#FF0000 Maroon key does not exist Print Page Previous Next Advertisements ”;
Scala Collections – Iterator
Scala Collections – Iterator ”; Previous Next An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it.next() will return the next element of the iterator and advance the state of the iterator. You can find out whether there are more elements to return using Iterator”s it.hasNext method. The most straightforward way to “step through” all the elements returned by an iterator is to use a while loop. Let us follow the following example program. Example object Demo { def main(args: Array[String]) { val it = Iterator(“a”, “number”, “of”, “words”) while (it.hasNext){ println(it.next()) } } } 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 number of words Find Min & Max Valued Element You can use it.min and it.max methods to find out the minimum and maximum valued elements from an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program. Example object Demo { def main(args: Array[String]) { val ita = Iterator(20,40,2,50,69, 90) val itb = Iterator(20,40,2,50,69, 90) println(“Maximum valued element ” + ita.max ) println(“Minimum valued element ” + itb.min ) } } 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 Maximum valued element 90 Minimum valued element 2 Find the Length of the Iterator You can use either it.size or it.length methods to find out the number of elements available in an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program. Example object Demo { def main(args: Array[String]) { val ita = Iterator(20,40,2,50,69, 90) val itb = Iterator(20,40,2,50,69, 90) println(“Value of ita.size : ” + ita.size ) println(“Value of itb.length : ” + itb.length ) } } 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 Value of ita.size : 6 Value of itb.length : 6 Print Page Previous Next Advertisements ”;
Scala Collections – Stream
Scala Collections – Stream ”; Previous Next Scala Stream is special list with lazy evaluation feature. In scala stream, elements are evaluated only when they are needed. Stream supports lazy computation and is performance savvy. Declaring Stream Variables The following is the syntax for declaring an Stream variable. Syntax val stream = 1 #:: 2 #:: 3 #:: Stream.empty Here, stream is declared as a stream of numbers. Here 1 is head of stream, 2, 3 are tail of stream. Stream.empty marks the end of the stream. Values can be retrived using take commands like the following − Command stream.take(2) Processing Stream Below is an example program of showing how to create, initialize and process Stream − Example import scala.collection.immutable.Stream object Demo { def main(args: Array[String]) = { val stream = 1 #:: 2 #:: 3 #:: Stream.empty // print stream println(stream) // Print first two elements stream.take(2).print println() // Create an empty stream val stream1: Stream[Int] = Stream.empty[Int] // Print element println(s”Stream: $stream1″) } } 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 Stream(1, <not computed>) 1, 2 Stream: Stream() Print Page Previous Next Advertisements ”;
Scala Collections – fold
Scala Collections – Fold Method ”; Previous Next fold() method is a member of TraversableOnce trait, it is used to collapse elements of collections. Syntax The following is the syntax of fold method. def fold[A1 >: A](z: A1)(op: (A1, A1) ? A1): A1 Here, fold method takes associative binary operator function as a parameter. This method returns the result as value. It considers first input as initial value and second input as a function (which takes accumulated value and current item as input). Usage Below is an example program of showing how to use fold method − Example object Demo { def main(args: Array[String]) = { val list = List(1, 2, 3 ,4) //apply operation to get sum of all elements of the list val result = list.fold(0)(_ + _) //print result println(result) } } Here we”ve passed 0 as initial value to fold function and then all values are added. 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 10 Print Page Previous Next Advertisements ”;
Scala Collections – ArrayBuffer ”; Previous Next Scala provides a data structure, the ArrayBuffer, which can change size when initial size falls short. As array is of fix size and more elements cannot be occupied in an array, ArrayBuffer is an alternative to array where size is flexible. Internally ArrayBuffer maintains an array of current size to store elements. When a new element is added, size is checked. In case underlying array is full then a new larger array is created and all elements are copied to larger array. Declaring ArrayBuffer Variables The following is the syntax for declaring an ArrayBuffer variable. Syntax var z = ArrayBuffer[String]() Here, z is declared as an array-buffer of Strings which is initially empty. Values can be added by using commands like the following − Command z += “Zara”; z += “Nuha”; z += “Ayan”; Processing ArrayBuffer Below is an example program of showing how to create, initialize and process ArrayBuffer − Example import scala.collection.mutable.ArrayBuffer object Demo { def main(args: Array[String]) = { var myList = ArrayBuffer(“Zara”,”Nuha”,”Ayan”) println(myList); // Add an element myList += “Welcome”; // Add two element myList += (“To”, “Tutorialspoint”); println(myList); // Remove an element myList -= “Welcome”; // print second element println(myList(1)); } } 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 ArrayBuffer(Zara, Nuha, Ayan) ArrayBuffer(Zara, Nuha, Ayan, Welcome, To, Tutorialspoint) Nuha Print Page Previous Next Advertisements ”;
Scala Collections – filter
Scala Collections – Filter Method ”; Previous Next filter() method is method used by List to select all elements which satisfies a given predicate. Syntax The following is the syntax of filter method. def filter(p: (A) => Boolean): List[A] Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list which satisfiles the given condition. Usage Below is an example program of showing how to use filter method − Example object Demo { def main(args: Array[String]) = { val list = List(3, 6, 9, 4, 2) // print list println(list) //apply operation val result = list.filter(x=>{x % 3 == 0}) //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(3, 6, 9, 4, 2) List(3, 6, 9) Print Page Previous Next Advertisements ”;
Scala Collections – Queue
Scala Collections – Queue ”; Previous Next Queue is First In First Out, FIFO data structure and allows to insert and retrieve elements in FIFO manner. Declaring Queue Variables The following is the syntax for declaring an Queue variable. Syntax val queue = Queue(1, 2, 3, 4, 5) Here, queue is declared as an Queue of numbers. Value can be added at front by using commands like the following − Command queue.enqueue(6) Value can be retrived at front by using commands like the following − Command queue.dequeue() Processing Queue Below is an example program of showing how to create, initialize and process Queue − Example import scala.collection.mutable.Queue object Demo { def main(args: Array[String]) = { var queue = Queue(1, 2, 3, 4, 5); // Print queue elements queue.foreach{(element:Int) => print(element + ” “)} println(); // Print first element println(“First Element: ” + queue.front) // Add an element queue.enqueue(6); // Print queue elements queue.foreach{(element:Int) => print(element+ ” “)} println(); // Remove an element var dq = queue.dequeue; // Print dequeued element println(“Dequeued Element: ” + dq) // Print queue elements queue.foreach{(element:Int) => print(element+ ” “)} } } 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 1 2 3 4 5 First Element: 1 1 2 3 4 5 6 Dequeued Element: 1 2 3 4 5 6 Print Page Previous Next Advertisements ”;