モジュールのレッスン (1/2)
セットとマップ
Beyond the ArrayList class (which represents an ordered list of elements), the Java Collections Framework offers two other fundamental interfaces: Set (for unique elements) and Map (for key-value associations).
Set: Collections of Unique Elements
A Set is a collection that cannot contain duplicate elements. Its most common implementation is HashSet, based internally on a hash table, which guarantees excellent performance for insertion, removal, and presence verification operations.
import java.util.HashSet;
import java.util.Set;
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // This insertion will be ignored since "Alice" is already present
System.out.println(uniqueNames.size()); // Prints 2
Map: Key-Value Associations
A Map maps unique keys to values. It cannot contain duplicate keys: each key is associated with at most one value. Its standard implementation is HashMap.
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> ageMap = new HashMap<>();
// Insert or update key-value pairs
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);
// Retrieve value by key
int aliceAge = ageMap.get("Alice"); // Returns 25
// Verify if a key or value exists
boolean hasBob = ageMap.containsKey("Bob"); // Returns true
Iterating over a Map
To iterate over key-value pairs, we can use a for-each loop on the set of entries (entrySet()) provided by the map.
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
System.out.println(entry.getKey() + " is " + entry.getValue() + " years old.");
}
Try it yourself
Complete the code by declaring a HashSet of strings named items. Add the elements 'apple', 'banana', and 'apple' again, then print the size of the set using System.out.println.
ヒントを表示
Remember that duplicates are not allowed in a `Set`, and `items.size()` will return the actual number of unique elements inserted.
3 回の試行後に解決策が利用可能になります
Complete the code by declaring a HashMap named ages with String keys and Integer values. Associate the key 'Alice' with 25 and the key 'Bob' with 30, then retrieve and print Bob's age.
ヒントを表示
Use the `put` method to insert pairs and the `get` method to retrieve values based on keys.
3 回の試行後に解決策が利用可能になります
Complete the code by checking if the countries map contains the key 'FR' and print the boolean result.
ヒントを表示
Use the `containsKey` method on the `countries` object to check for the presence of the required key.
3 回の試行後に解決策が利用可能になります