Map

PHOTO EMBED

Sun Dec 25 2022 22:04:31 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka #java #generics #map

//Map defines a generic interface for an object that holds key-value pairs as elements. The key is used to retrieve (like the index in an array or List) some value. A key must be unique and map to exactly one value.
//The HashMap defines no specific ordering for the keys and is the most optimized implementation for retrieving values.
//The LinkedHashMap keeps the keys in insertion order and is slightly less optimal than the HashMap.
//The TreeMap keeps keys in their natural order (or some custom order defined using a Comparator). This implementation has a significant performance decrease compared to HashMap and LinkedHashMap but is great when needing to keep keys sorted.
//A Map has the following methods for accessing its elements:
//put(): Sets the value that key maps to. Note that this method replaces the value key mapped to if the key was already present in the Map.
//get(): Gets, but does not remove, the value the provided key argument points to if it exists. This method returns null if the key is not in the Map.

Map<String, String> myMap = new HashMap<>();
 
myMap.put("Hello", "World") // { "Hello" -> "World" }
myMap.put("Name", "John") //   { "Hello" -> "World" }, { "Name" -> "John" }
 
String result = myMap.get("Hello") // returns "World" 
String noResult = myMap.get("Jack") // return `null`

// Given a map, `myMap`, with the following key-value pairs { "Hello" -> "World" }, { "Name" -> "John"}
for (Map.Entry<String, String> pair: myMap.entrySet()){
  System.out.println("key: "+pair.getKey()+", value: "+pair.getValue());
}
// OUTPUT TERMINAL:
// key: Name, value: John
// key: Hello, value: World
content_copyCOPY