Scala - Using for and foreach with Maps Code Example

The code for Using for and foreach with Maps

val person = Map(
"Alvin Alexander" -> 35,
"Alice Walker" -> 78,
"Mark Zuckerberg" -> 38
)
// You can print the person names 
// and age using for like this
for ((name,age) <- person) println(s"Name: $name, Age: $age")

// You can also print 
// with foreach like this
person.foreach {
case(name, age) => println(s"Name: $name, Age: $age")
}
/*
Output:
Name: Alvin Alexander, Age: 35
Name: Alice Walker, Age: 78
Name: Mark Zuckerberg, Age: 38
Name: Alvin Alexander, Age: 35
Name: Alice Walker, Age: 78
Name: Mark Zuckerberg, Age: 38
*/
Code by IncludeHelp, on August 8, 2022 02:01

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.