ArrayList and LinkedList are part of java.util.collections framework and Maps are part of java.util.Map
List ,Set ,Queue and Dequeue inherit directly from collections.
Maps hold key,value pairs
Keys are unique in a map.so what that means is if we put two values for the same keys in a map it will override the previous value and then we can only access the second value using that key
So to avoid adding values to keys that already exist we can check if key already exists using
if(languages.containsKey("Python")) //where langauges is a map and Python is a key
Then we can use a for loop to iterate through each key value pair for a map
for(String key:languages.keySet()){System.out.println(key +" : "+languages.get(key));}
We can even print just the values of a map and not the keys by doing the below
for(String value:languages.values()){ System.out.println(value) }
To print only keys from a map
for(String exit:exits.keySet()){
System.out.print(exit+ ", ");
}
Other than key set we can print a map like this
System.out.println(exits.toString());
To print Map in a more readable form we can do use an for loop on keySet and do something like this as we did above as well
for (String key : languages.keySet()) {
System.out.println(key + " : " + languages.get(key));
}
To remove a value
languages.remove("MySql");
To remove if key value pairs match,pass both key and value as arguments and it will only remove and return true if both values match and hence we can use a if condition
if (languages.remove("JavaScript", "Only remove if key values match")) {
System.out.println("JavaScript removed");
}
To replace
languages.replace("Python","Getting famous for machine learning");
Similar to remove , replace only if key value pairs match
if (languages.replace("JavaScript", "Only replace if old key value pairs match in the Map","New value for Javascript"))
{System.out.println("JavaScript value replaced");}
We can create a copy of a Map by passing that map as arguments to new map constructor.
Map<String, String> newMap = new HashMap<>(languages);