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 ”;

Rust – Enums

Rust – Enums ”; Previous Next In Rust programming, when we have to select a value from a list of possible variants we use enumeration data types. An enumerated type is declared using the enum keyword. Following is the syntax of enum − enum enum_name { variant1, variant2, variant3 } Illustration: Using an Enumeration The example declares an enum − GenderCategory, which has variants as Male and Female. The print! macro displays value of the enum. The compiler will throw an error the trait std::fmt::Debug is not implemented for GenderCategory. The attribute #[derive(Debug)] is used to suppress this error. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Male,Female } fn main() { let male = GenderCategory::Male; let female = GenderCategory::Female; println!(“{:?}”,male); println!(“{:?}”,female); } Output Male Female Struct and Enum The following example defines a structure Person. The field gender is of the type GenderCategory (which is an enum) and can be assigned either Male or Female as value. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Male,Female } // The `derive` attribute automatically creates the implementation // required to make this `struct` printable with `fmt::Debug`. #[derive(Debug)] struct Person { name:String, gender:GenderCategory } fn main() { let p1 = Person { name:String::from(“Mohtashim”), gender:GenderCategory::Male }; let p2 = Person { name:String::from(“Amy”), gender:GenderCategory::Female }; println!(“{:?}”,p1); println!(“{:?}”,p2); } The example creates objects p1 and p2 of type Person and initializes the attributes, name and gender for each of these objects. Output Person { name: “Mohtashim”, gender: Male } Person { name: “Amy”, gender: Female } Option Enum Option is a predefined enum in the Rust standard library. This enum has two values − Some(data) and None. Syntax enum Option<T> { Some(T), //used to return a value None // used to return null, as Rust doesn”t support the null keyword } Here, the type T represents value of any type. Rust does not support the null keyword. The value None, in the enumOption, can be used by a function to return a null value. If there is data to return, the function can return Some(data). Let us understand this with an example − The program defines a function is_even(), with a return type Option. The function verifies if the value passed is an even number. If the input is even, then a value true is returned, else the function returns None. fn main() { let result = is_even(3); println!(“{:?}”,result); println!(“{:?}”,is_even(30)); } fn is_even(no:i32)->Option<bool> { if no%2 == 0 { Some(true) } else { None } } Output None Some(true) Match Statement and Enum The match statement can be used to compare values stored in an enum. The following example defines a function, print_size, which takes CarType enum as parameter. The function compares the parameter values with a pre-defined set of constants and displays the appropriate message. enum CarType { Hatch, Sedan, SUV } fn print_size(car:CarType) { match car { CarType::Hatch => { println!(“Small sized car”); }, CarType::Sedan => { println!(“medium sized car”); }, CarType::SUV =>{ println!(“Large sized Sports Utility car”); } } } fn main(){ print_size(CarType::SUV); print_size(CarType::Hatch); print_size(CarType::Sedan); } Output Large sized Sports Utility car Small sized car medium sized car Match with Option The example of is_even function, which returns Option type, can also be implemented with match statement as shown below − fn main() { match is_even(5) { Some(data) => { if data==true { println!(“Even no”); } }, None => { println!(“not even”); } } } fn is_even(no:i32)->Option<bool> { if no%2 == 0 { Some(true) } else { None } } Output not even Match & Enum with Data Type It is possible to add data type to each variant of an enum. In the following example, Name and Usr_ID variants of the enum are of String and integer types respectively. The following example shows the use of match statement with an enum having a data type. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Name(String),Usr_ID(i32) } fn main() { let p1 = GenderCategory::Name(String::from(“Mohtashim”)); let p2 = GenderCategory::Usr_ID(100); println!(“{:?}”,p1); println!(“{:?}”,p2); match p1 { GenderCategory::Name(val)=> { println!(“{}”,val); } GenderCategory::Usr_ID(val)=> { println!(“{}”,val); } } } Output Name(“Mohtashim”) Usr_ID(100) Mohtashim 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

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 ”;

Rust – Slices

Rust – Slices ”; Previous Next A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime. Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing. For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays. Syntax let sliced_value = &data_structure[start_index..end_index] The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string. The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8. The following code fetches 5 characters from the string (starting from index 4). fn main() { let n1 = “Tutorials”.to_string(); println!(“length of string is {}”,n1.len()); let c1 = &n1[4..9]; // fetches characters at 4,5,6,7, and 8 indexes println!(“{}”,c1); } Output length of string is 9 rials Illustration – Slicing an integer array The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length. fn main(){ let data = [10,20,30,40,50]; use_slice(&data[1..4]); //this is effectively borrowing elements for a while } fn use_slice(slice:&[i32]) { // is taking a slice or borrowing a part of an array of i32s println!(“length of slice is {:?}”,slice.len()); println!(“{:?}”,slice); } Output length of slice is 3 [20, 30, 40] Mutable Slices The &mut keyword can be used to mark a slice as mutable. fn main(){ let mut data = [10,20,30,40,50]; use_slice(&mut data[1..4]); // passes references of 20, 30 and 40 println!(“{:?}”,data); } fn use_slice(slice:&mut [i32]) { println!(“length of slice is {:?}”,slice.len()); println!(“{:?}”,slice); slice[0] = 1010; // replaces 20 with 1010 } Output length of slice is 3 [20, 30, 40] [10, 1010, 30, 40, 50] The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array. Print Page Previous Next Advertisements ”;

Rust – Generic Types

Rust – Generic Types ”; Previous Next Generics are a facility to write code for multiple contexts with different types. In Rust, generics refer to the parameterization of data types and traits. Generics allows to write more concise and clean code by reducing code duplication and providing type-safety. The concept of Generics can be applied to methods, functions, structures, enumerations, collections and traits. The <T> syntax known as the type parameter, is used to declare a generic construct. T represents any data-type. Illustration: Generic Collection The following example declares a vector that can store only integers. fn main(){ let mut vector_integer: Vec<i32> = vec![20,30]; vector_integer.push(40); println!(“{:?}”,vector_integer); } Output [20, 30, 40] Consider the following snippet − fn main() { let mut vector_integer: Vec<i32> = vec![20,30]; vector_integer.push(40); vector_integer.push(“hello”); //error[E0308]: mismatched types println!(“{:?}”,vector_integer); } The above example shows that a vector of integer type can only store integer values. So, if we try to push a string value into the collection, the compiler will return an error. Generics make collections more type safe. Illustration: Generic Structure The type parameter represents a type, which the compiler will fill in later. struct Data<T> { value:T, } fn main() { //generic type of i32 let t:Data<i32> = Data{value:350}; println!(“value is :{} “,t.value); //generic type of String let t2:Data<String> = Data{value:”Tom”.to_string()}; println!(“value is :{} “,t2.value); } The above example declares a generic structure named Data. The <T> type indicates some data type. The main() function creates two instances − an integer instance and a string instance, of the structure. Output value is :350 value is :Tom Traits Traits can be used to implement a standard set of behaviors (methods) across multiple structures. Traits are like interfaces in Object-oriented Programming. The syntax of trait is as shown below − Declare a Trait trait some_trait { //abstract or method which is empty fn method1(&self); // this is already implemented , this is free fn method2(&self){ //some contents of method2 } } Traits can contain concrete methods (methods with body) or abstract methods (methods without a body). Use a concrete method if the method definition will be shared by all structures implementing the Trait. However, a structure can choose to override a function defined by the trait. Use abstract methods if the method definition varies for the implementing structures. Syntax – Implement a Trait impl some_trait for structure_name { // implement method1() there.. fn method1(&self ){ } } The following examples defines a trait Printable with a method print(), which is implemented by the structure book. fn main(){ //create an instance of the structure let b1 = Book { id:1001, name:”Rust in Action” }; b1.print(); } //declare a structure struct Book { name:&”static str, id:u32 } //declare a trait trait Printable { fn print(&self); } //implement the trait impl Printable for Book { fn print(&self){ println!(“Printing book with id:{} and name {}”,self.id,self.name) } } Output Printing book with id:1001 and name Rust in Action Generic Functions The example defines a generic function that displays a parameter passed to it. The parameter can be of any type. The parameter’s type should implement the Display trait so that its value can be printed by the println! macro. use std::fmt::Display; fn main(){ print_pro(10 as u8); print_pro(20 as u16); print_pro(“Hello TutorialsPoint”); } fn print_pro<T:Display>(t:T){ println!(“Inside print_pro generic function:”); println!(“{}”,t); } Output Inside print_pro generic function: 10 Inside print_pro generic function: 20 Inside print_pro generic function: Hello TutorialsPoint Print Page Previous Next Advertisements ”;