In this code-along, you'll implement a comprehensive Sets solution that demonstrates:
// Creating different types of Sets Set<String> hashSet = new HashSet<>(); // No guaranteed order, fastest performance Set<String> linkedHashSet = new LinkedHashSet<>(); // Maintains insertion order Set<String> treeSet = new TreeSet<>(); // Elements stored in natural order (sorted) // Basic operations hashSet.add("element"); // Add an element boolean contained = hashSet.contains("element"); // Check if element exists boolean removed = hashSet.remove("element"); // Remove an element int size = hashSet.size(); // Get number of elements boolean isEmpty = hashSet.isEmpty(); // Check if set is empty // Set operations using built-in methods Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "d")); // Union: set1 ∪ set2 = {a, b, c, d} Set<String> union = new HashSet<>(set1); union.addAll(set2); // Intersection: set1 ∩ set2 = {b, c} Set<String> intersection = new HashSet<>(set1); intersection.retainAll(set2); // Difference: set1 - set2 = {a} Set<String> difference = new HashSet<>(set1); difference.removeAll(set2);
In this code-along, you'll implement a Maps solution that demonstrates:
// Creating different types of Maps Map<String, Integer> hashMap = new HashMap<>(); // No guaranteed order, fastest performance Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); // Maintains insertion order Map<String, Integer> treeMap = new TreeMap<>(); // Keys stored in natural order (sorted) // Basic operations hashMap.put("key1", 100); // Add/update a key-value pair Integer value = hashMap.get("key1"); // Retrieve a value by key boolean hasKey = hashMap.containsKey("key1"); // Check if key exists boolean hasValue = hashMap.containsValue(100); // Check if value exists Integer removed = hashMap.remove("key1"); // Remove entry by key int size = hashMap.size(); // Get number of entries // Handling missing keys Integer valueOrDefault = hashMap.getOrDefault("missing", 0); // Returns 0 if key not found // Iteration methods // 1. Using entrySet() - most efficient for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); System.out.println(key + " -> " + val); } // 2. Using keySet() for (String key : hashMap.keySet()) { System.out.println(key + " -> " + hashMap.get(key)); } // 3. Using values() (lose access to keys) for (Integer val : hashMap.values()) { System.out.println("Value: " + val); }