முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 6 · பாடம் 1 இன் 2பாடத்திட்டத்தில் 11/14~15 min
தொகுதி பாடங்கள் (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.

Code
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.

Code
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.

Code
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
    System.out.println(entry.getKey() + " is " + entry.getValue() + " years old.");
}

Try it yourself

உடற்பயிற்சி#java.m6.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

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 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

உடற்பயிற்சி#java.m6.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

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 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

உடற்பயிற்சி#java.m6.l1.e3
முயற்சிகள்: 0ஏற்றுகிறது…

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 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்