Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,864 questions

51,786 answers

573 users

How to iterate over a HashMap in Scala

3 Answers

0 votes
import scala.collection.mutable.HashMap

val map = HashMap("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4)

for ((key, value) <- map) {
  println(s"Key: $key, Value: $value")
}



/*
run:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
Key: d, Value: 4
 
*/

 



answered Mar 3, 2025 by avibootz
0 votes
import scala.collection.mutable.HashMap

val map = HashMap("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4)

map.foreach { case (key, value) =>
  println(s"Key: $key, Value: $value")
}



/*
run:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
Key: d, Value: 4
 
*/

 



answered Mar 3, 2025 by avibootz
0 votes
import scala.collection.mutable.HashMap

val map = HashMap("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4)

// Iterating over keys
for (key <- map.keys) {
  println(s"Key: $key")
}

// Iterating over values
for (value <- map.values) {
  println(s"Value: $value")
}


/*
run:

Key: a
Key: b
Key: c
Key: d
Value: 1
Value: 2
Value: 3
Value: 4
 
*/

 



answered Mar 3, 2025 by avibootz

Related questions

3 answers 169 views
2 answers 217 views
217 views asked Jun 2, 2021 by avibootz
1 answer 64 views
1 answer 118 views
2 answers 196 views
2 answers 192 views
192 views asked Jan 21, 2022 by avibootz
...