Java Collection, HashMap Exercises: Copy all of the mappings from the specified map to another map
Java Collection, HashMap Exercises: Exercise-3 with Solution
Write a Java program to copy all of the mappings from the specified map to another map.
Sample Solution:-
Java Code:
import java.util.*;
public class Example3 {
public static void main(String args[]) {
// create two hash maps
HashMap <Integer,String> hash_map1 = new HashMap <Integer,String> ();
HashMap <Integer,String> hash_map2 = new HashMap <Integer,String> ();
// populate hash maps
hash_map1.put(1, "Red");
hash_map1.put(2, "Green");
hash_map1.put(3, "Black");
System.out.println("\nValues in first map: " + hash_map1);
hash_map2.put(4, "White");
hash_map2.put(5, "Blue");
hash_map2.put(6, "Orange");
System.out.println("\nValues in second map: " + hash_map2);
// put all values in secondmap
hash_map2.putAll(hash_map1);
System.out.println("\nNow values in second map: " + hash_map2);
}
}
Sample Output:
Values in first map: {1=Red, 2=Green, 3=Black} Values in second map: {4=White, 5=Blue, 6=Orange} Now values in second map: {1=Red, 2=Green, 3=Black, 4=White, 5=Blue, 6= Orange}
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Count the number of key-value (size) mappings in a map.
Next: Remove all the mappings from a map.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework