java_map_interface

Java Map Interface

Return to Java Map, Map, Functional Java, Java DevOps - Java SRE - Java CI/CD, Cloud Native Java - Java Microservices - Serverless Java, Java Security - Java DevSecOps, Java Concurrency, Java Data Science - Java and Databases, Java Machine Learning, Java Bibliography, Java Courses, Java Glossary, Awesome Java, Java GitHub, Java Topics

“ (OCP17SelBoy 2022)

Using the Map Interface

“You use a Map when you want to identify values by a key. For example, when you use the contact list in your phone, you look up “George” rather than looking through each phone number in turn.” (OCP17SelBoy 2022)

“You can envision a Map as shown in Figure 9.8. You don't need to know the names of the specific interfaces that the different maps implement, but you do need to know that TreeMap is sorted.” (OCP17SelBoy 2022)

FIGURE 9.8 Example of a Map

“The main thing that all Map classes have in common is that they have keys and values. Beyond that, they each offer different functionality. We look at the implementations you need to know and the available methods.” (OCP17SelBoy 2022)

Map.of() and Map.copyOf()

“Just like List and Set, there is a factory method to create a Map. You pass any number of pairs of keys and values.” (OCP17SelBoy 2022)

Map.of(”key1“, ”value1“, ”key2“, ”value2“);

“Unlike List and Set, this is less than ideal. Passing keys and values is harder to read because you have to keep track of which parameter is which. Luckily, there is a better way. Map also provides a method that lets you supply key/value pairs.” (OCP17SelBoy 2022)

Map.ofEntries( Map.entry(”key1“, ”value1“), Map.entry(”key2“, ”value2“));

“Now we can't forget to pass a value. If we leave out a parameter, the entry() method won't compile. Conveniently, Map.copyOf(map) works just like the List and Set interface copyOf() methods.” (OCP17SelBoy 2022)

Comparing Map Implementations

Java Comparing Map Implementations

Comparing Map Implementations

“A HashMap stores the keys in a hash table. This means that it uses the hashCode() method of the keys to retrieve their values more efficiently.” (OCP17SelBoy 2022)

“The main benefit is that adding elements and retrieving the element by key both have constant time. The trade-off is that you lose the order in which you inserted the elements. Most of the time, you aren't concerned with this in a map anyway. If you were, you could use LinkedHashMap, but that's not in scope for the exam.” (OCP17SelBoy 2022)

“A TreeMap stores the keys in a sorted tree structure. The main benefit is that the keys are always in sorted order. Like a TreeSet, the trade-off is that adding and checking whether a key is present takes longer as the tree grows larger.” (OCP17SelBoy 2022)

Working with Map Methods

Java Working with Map Methods

Working with Map Methods

“Given that Map doesn't extend Collection, more methods are specified on the Map interface. Since there are both keys and values, we need generic type parameters for both. The class uses K for key and V for value. The methods you need to know for the exam are in Table 9.6. Some of the method signatures are simplified to make them easier to understand.” (OCP17SelBoy 2022)

Map Methods

Java Map Methods

TABLE 9.6 Map methods

Method Description

public void clear() Removes all keys and values from map.

public boolean containsKey(Object key) Returns whether key is in map.

public boolean containsValue(Object value) Returns whether value is in map.

public Set<Map.Entry<K,V» entrySet() Returns Set of key/value pairs.

public void forEach(BiConsumer<K key, V value>) Loops through each key/value pair.

public V get(Object key) Returns value mapped by key or null if none is mapped.

public V getOrDefault(Object key, V defaultValue) Returns value mapped by key or default value if none is mapped.

public boolean isEmpty() Returns whether map is empty.

public Set<K> keySet() Returns set of all keys.

public V merge(K key, V value, Function(<V, V, V> func)) Sets value if key not set. Runs function if key is set, to determine new value. Removes if value is null.

public V put(K key, V value) Adds or replaces key/value pair. Returns previous value or null.

public V putIfAbsent(K key, V value) Adds value if key not present and returns null. Otherwise, returns existing value.

public V remove(Object key) Removes and returns value mapped to key. Returns null if none.

public V replace(K key, V value) Replaces value for given key if key is set. Returns original value or null if none.

public void replaceAll(BiFunction<K, V, V> func) Replaces each value with results of function.

public int size() Returns number of entries (key/value pairs) in map.

public Collection<V> values() Returns Collection of all values.

While Table 9.6 is a pretty long list of methods, don't worry; many of the names are straightforward. Also, many exist as a convenience. For example, containsKey() can be replaced with a get() call that checks if the result is null. Which one you use is up to you.“ (OCP17SelBoy 2022)

Calling Basic Map Methods

Java Calling Basic Map Methods

Calling Basic Methods

“Let's start out by comparing the same code with two Map types. First up is HashMap:” (OCP17SelBoy 2022)

Map<String, String> map = new HashMap<>(); map.put(”koala“, ”bamboo“); map.put(“lion”, “meat”); map.put(“giraffe”, “leaf”); String food = map.get(”koala“); // bamboo for (String key: map.keySet()) System.out.print(key + ”,“); // koala,giraffe,lion,

“Here we use the put() method to add key/value pairs to the map and get() to get a value given a key. We also use the keySet() method to get all the keys.” (OCP17SelBoy 2022)

Java uses the hashCode() of the key to determine the order. The order here happens not to be sorted order or the order in which we typed the values. Now let's look at TreeMap:“ (OCP17SelBoy 2022)

Map<String, String> map = new TreeMap<>(); map.put(”koala“, ”bamboo“); map.put(“lion”, “meat”); map.put(“giraffe”, “leaf”); String food = map.get(”koala“); // bamboo for (String key: map.keySet()) System.out.print(key + ”,“); // giraffe,koala,lion,

TreeMap sorts the keys as we would expect. If we called values() instead of keySet(), the order of the values would correspond to the order of the keys.“ (OCP17SelBoy 2022)

With our same map, we can try some boolean checks:

System.out.println(map.contains(“lion”)); // DOES NOT COMPILE System.out.println(map.containsKey(“lion”)); // true System.out.println(map.containsValue(“lion”)); // false System.out.println(map.size()); // 3 map.clear(); System.out.println(map.size()); // 0 System.out.println(map.isEmpty()); // true

“The first line is a little tricky. The contains() method is on the Collection interface but not the Map interface. The next two lines show that keys and values are checked separately. We can see that there are three key/value pairs in our map. Then we clear out the contents of the map and see that there are zero elements and it is empty.” (OCP17SelBoy 2022)

In the following sections, we show Map methods you might not be as familiar with.

Iterating Through a Map

Java Iterating Through a Map

Iterating through a Map

“You saw the forEach() method earlier in the chapter. Note that it works a little differently on a Map. This time, the lambda used by the forEach() method has two parameters: the key and the value. Let's look at an example, shown here:” (OCP17SelBoy 2022)

Map<Integer, Character> map = new HashMap<>(); map.put(1, 'a'); map.put(2, 'b'); map.put(3, 'c'); map.forEach1);

“The lambda has both the key and value as the parameters. It happens to print out the value but could do anything with the key and/or value. Interestingly, since we don't care about the key, this particular code could have been written with the values() method and a method reference instead.” (OCP17SelBoy 2022)

map.values().forEach(System.out::println);

“Another way of going through all the data in a map is to get the key/value pairs in a Set. Java has a static interface inside Map called Entry. It provides methods to get the key and value of each pair.” (OCP17SelBoy 2022)

map.entrySet().forEach(e → System.out.println(e.getKey() + ” “ + e.getValue()));

Getting Values Safely

Java Getting Map Values Safely

Getting Values Safely

“The get() method returns null if the requested key is not in the map. Sometimes you prefer to have a different value returned. Luckily, the getOrDefault() method makes this easy. Let's compare the two methods:” (OCP17SelBoy 2022)

3: Map<Character, String> map = new HashMap<>(); 4: map.put('x', “spot”); 5: System.out.println(“X marks the ” + map.get('x')); 6: System.out.println(“X marks the ” + map.getOrDefault('x', ”“)); 7: System.out.println(“Y marks the ” + map.get('y')); 8: System.out.println(“Y marks the ” + map.getOrDefault('y', ”“));

This code prints the following:

X marks the spot X marks the spot Y marks the null Y marks the

“As you can see, lines 5 and 6 have the same output because get() and getOrDefault() behave the same way when the key is present. They return the value mapped by that key. Lines 7 and 8 give different output, showing that get() returns null when the key is not present. By contrast, getOrDefault() returns the empty string we passed as a parameter.” (OCP17SelBoy 2022)

Replacing Values

Replacing Values

“These methods are similar to the List version, except a key is involved:” (OCP17SelBoy 2022)

21: Map<Integer, Integer> map = new HashMap<>(); 22: map.put(1, 2); 23: map.put(2, 4); 24: Integer original = map.replace(2, 10); // 4 25: System.out.println(map); // {1=2, 2=10} 26: map.replaceAll((k, v) → k + v); 27: System.out.println(map); // {1=3, 2=12}

Line 24 replaces the value for key 2 and returns the original value. Line 26 calls a function and sets the value of each element of the map to the result of that function. In our case, we added the key and value together.“ (OCP17SelBoy 2022)

Putting if Absent

Putting if Absent

“The putIfAbsent() method sets a value in the map but skips it if the value is already set to a non-null value.” (OCP17SelBoy 2022)

Map<String, String> favorites = new HashMap<>(); favorites.put(“Jenny”, “Bus Tour”); favorites.put(“Tom”, null); favorites.putIfAbsent(“Jenny”, “Tram”); favorites.putIfAbsent(“Sam”, “Tram”); favorites.putIfAbsent(“Tom”, “Tram”); System.out.println(favorites); // {Tom=Tram, Jenny=Bus Tour, Sam=Tram}

“As you can see, Jenny's value is not updated because one was already present. Sam wasn't there at all, so he was added. Tom was present as a key but had a null value. Therefore, he was added as well.” (OCP17SelBoy 2022)

Merging Data

Merging Data

“The merge() method adds logic of what to choose. Suppose we want to choose the ride with the longest name. We can write code to express this by passing a mapping function to the merge() method:” (OCP17SelBoy 2022)

11: BiFunction<String, String, String> mapper = (v1, v2) 12: → v1.length()> v2.length() ? v1: v2; 13: 14: Map<String, String> favorites = new HashMap<>(); 15: favorites.put(“Jenny”, “Bus Tour”); 16: favorites.put(“Tom”, “Tram”); 17: 18: String jenny = favorites.merge(“Jenny”, “Skyride”, mapper); 19: String tom = favorites.merge(“Tom”, “Skyride”, mapper); 20: 21: System.out.println(favorites); // {Tom=Skyride, Jenny=Bus Tour} 22: System.out.println(jenny); // Bus Tour 23: System.out.println(tom); // Skyride

“The code on lines 11 and 12 takes two parameters and returns a value. Our implementation returns the one with the longest name. Line 18 calls this mapping function, and it sees that Bus Tour is longer than Skyride, so it leaves the value as Bus Tour. Line 19 calls this mapping function again. This time, Tram is shorter than Skyride, so the map is updated. Line 21 prints out the new map contents. Lines 22 and 23 show that the result is returned from merge().” (OCP17SelBoy 2022)

“The merge() method also has logic for what happens if null values or missing keys are involved. In this case, it doesn't call the BiFunction at all, and it simply uses the new value.” (OCP17SelBoy 2022)

BiFunction<String, String, String> mapper = (v1, v2) → v1.length()> v2.length() ? v1 : v2; Map<String, String> favorites = new HashMap<>(); favorites.put(“Sam”, null); favorites.merge(“Tom”, “Skyride”, mapper); favorites.merge(“Sam”, “Skyride”, mapper); System.out.println(favorites); // {Tom=Skyride, Sam=Skyride}

“Notice that the mapping function isn't called. If it were, we'd have a NullPointerException. The mapping function is used only when there are two actual values to decide between.” (OCP17SelBoy 2022)

“The final thing to know about merge() is what happens when the mapping function is called and returns null. The key is removed from the map when this happens:” (OCP17SelBoy 2022)

BiFunction<String, String, String> mapper = (v1, v2) → null; Map<String, String> favorites = new HashMap<>(); favorites.put(“Jenny”, “Bus Tour”); favorites.put(“Tom”, “Bus Tour”); favorites.merge(“Jenny”, “Skyride”, mapper); favorites.merge(“Sam”, “Skyride”, mapper); System.out.println(favorites); // {Tom=Bus Tour, Sam=Skyride}

“Tom was left alone since there was no merge() call for that key. Sam was added since that key was not in the original list. Jenny was removed because the mapping function returned null.” (OCP17SelBoy 2022)

Table 9.7 shows all of these scenarios as a reference.

TABLE 9.7 Behavior of the merge() method“ (OCP17SelBoy 2022)

If the requested key ________ And mapping function returns ________ Then:

Has a null value in map N/A (mapping function not called) Update key's value in map with value parameter

Has a non-null value in map null Remove key from map

Has a non-null value in map A non-null value Set key to mapping function result

Is not in map N/A (mapping function not called) Add key with value parameter to map directly without calling mapping function

Comparing Collection Types

“We conclude this section with a review of all the collection classes. Make sure that you can fill in Table 9.8 to compare the four collection types from memory.” (OCP17SelBoy 2022)

TABLE 9.8 Java Collections Framework types“ (OCP17SelBoy 2022)

Type Can contain duplicate elements? Elements always ordered? Has keys and values? Must add/remove in specific order?

List Yes Yes (by index) No No

Map Yes (for values) No Yes No

Queue Yes Yes (retrieved in defined order) No Yes

Set No No No No

Additionally, make sure you can fill in Table 9.9 to describe the types on the exam.

TABLE 9.9 Collection attributes“ (OCP17SelBoy 2022)

Type Java Collections Framework interface Sorted? Calls hashCode? Calls compareTo?

ArrayDeque Deque No No No

ArrayList List No No No

HashMap Map No Yes No

HashSet Set No Yes No

LinkedList List, Deque No No No

TreeMap Map Yes No Yes

TreeSet Set Yes No Yes

Research More

Fair Use Sources

Java: Java Fundamentals, Java Inventor - Java Language Designer: James Gosling of Sun Microsystems, Java Docs, JDK, JVM, JRE, Java Keywords, JDK 17 API Specification, java.base, Java Built-In Data Types, Java Data Structures - Java Algorithms, Java Syntax, Java OOP - Java Design Patterns, Java Installation, Java Containerization, Java Configuration, Java Compiler, Java Transpiler, Java IDEs (IntelliJ - Eclipse - NetBeans), Java Development Tools, Java Linter, JetBrains, Java Testing (JUnit, Hamcrest, Mockito), Java on Android, Java on Windows, Java on macOS, Java on Linux, Java DevOps - Java SRE, Java Data Science - Java DataOps, Java Machine Learning, Java Deep Learning, Functional Java, Java Concurrency, Java History,

Java Bibliography (Effective Java, Head First Java, Java - A Beginner's Guide by Herbert Schildt, Java Concurrency in Practice, Clean Code by Robert C. Martin, Java - The Complete Reference by Herbert Schildt, Java Performance by Scott Oaks, Thinking in Java, Java - How to Program by Paul Deitel, Modern Java in Action, Java Generics and Collections by Maurice Naftalin, Spring in Action, Java Network Programming by Elliotte Rusty Harold, Functional Programming in Java by Pierre-Yves Saumont, Well-Grounded Java Developer, Second Edition, Java Module System by Nicolai Parlog

), Manning Java Series, Java Glossary, Java Topics, Java Courses, Java Security - Java DevSecOps, Java Standard Library, Java Libraries, Java Frameworks, Java Research, Java GitHub, Written in Java, Java Popularity, Java Awesome List, Java Versions. (navbar_java and navbar_java_detailed - see also navbar_jvm, navbar_java_concurrency, navbar_java_standard_library, navbar_java_libraries, navbar_java_navbars)


© 1994 - 2024 Cloud Monk Losang Jinpa or Fair Use. Disclaimers

SYI LU SENG E MU CHYWE YE. NAN. WEI LA YE. WEI LA YE. SA WA HE.


java_map_interface.txt · Last modified: 2024/04/28 03:40 by 127.0.0.1