*Mastering Java Data Structures: A Deep Dive into the Collections Framework
Java has Collections Framework which is Java's built-in toolkit for handling data. It offers a set of
ready-made tools, like interfaces and classes, that make it easy to organize and work with your data
effectively.
Here's a quick overview of the core interfaces and their popular implementations I explored:
### *1. List Interface (Ordered, Allows Duplicates)*
* *ArrayList*: A resizable array. Ideal for fast random access.
List<String> itemList = new ArrayList<>();
itemList.add("Apple"); // Add element
itemList.add("Banana");
itemList.remove("Apple"); // Remove element
String rstItem = itemList.get(0); // Access by index
// Output: [Banana]
* *LinkedList*: E cient for frequent insertions and deletions at ends.
List<String> productList = new LinkedList<>();
productList.addFirst("Laptop"); // Add to beginning
productList.addLast("Mouse"); // Add to end
productList.removeFirst(); // Remove from beginning
String lastProduct = ((LinkedList<String>) productList).getLast(); // Access last element
// Output: [Mouse]
* *List Sorting*: You can easily sort List implementations using Collections.sort().
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
Collections.sort(names); // Sorts alphabetically
// Output: [Alice, Bob, Charlie]
*Di erences (List):*
* *ArrayList*: Backed by a dynamic array. Fast for get(index). Slower for add/remove in the
middle (requires shifting elements).
* *LinkedList*: Backed by a doubly-linked list. Fast for addFirst/addLast/removeFirst/
removeLast. Slower for get(index) (requires traversing).
*Common List Methods:*
Let's consider List<String> mySampleList = new ArrayList<>();
* mySampleList.add("Element"); // Appends an element to the end.
* mySampleList.add(0, "First"); // Inserts an element at a speci ed position.
* String element = mySampleList.get(0); // Returns the element at the speci ed position.
* mySampleList.set(0, "New First"); // Replaces the element at the speci ed position.
* mySampleList.remove("Element"); // Removes the rst occurrence of the speci ed element.
* mySampleList.remove(0); // Removes the element at the speci ed position.
* int size = mySampleList.size(); // Returns the number of elements.
* boolean contains = mySampleList.contains("Element"); // Checks if the list contains the
speci ed element.
* boolean isEmpty = mySampleList.isEmpty(); // Checks if the list has no elements.
* mySampleList.clear(); // Removes all elements.
* Collections.sort(mySampleList); // Sorts the list (utility method).
* int index = mySampleList.indexOf("Element"); // Returns the index of the rst occurrence.
ff
fi
fi
ffi
fi
fi
fi
fi
fi
fi
fi
### *2. Set Interface (Unique Elements)*
* *HashSet*: O ers excellent performance for add, remove, and contains. No guaranteed order.
Set<Integer> uniqueIds = new HashSet<>();
uniqueIds.add(101); // Add element
uniqueIds.add(101); // Duplicate ignored
uniqueIds.add(102);
uniqueIds.remove(101); // Remove element
boolean containsId = uniqueIds.contains(102); // Check existence
// Output (unordered): [102] (order may vary)
* *TreeSet*: Stores unique elements in natural sorted order.
Set<String> sortedNames = new TreeSet<>();
sortedNames.add("Charlie");
sortedNames.add("Alice");
sortedNames.add("Bob");
boolean removed = sortedNames.remove("Bob");
// Output: [Alice, Charlie] (sorted alphabetically)
* *LinkedHashSet*: Maintains insertion order while ensuring uniqueness.
Set<Double> orderedValues = new LinkedHashSet<>();
orderedValues.add(3.14);
orderedValues.add(1.618);
orderedValues.add(3.14); // Duplicate ignored
boolean hasValue = orderedValues.contains(1.618);
// Output: [3.14, 1.618] (insertion order preserved)
*Di erences (Set):*
* *HashSet*: Best performance (average O(1) for operations). No order guaranteed.
* *TreeSet*: Stores elements in natural sorted order (or by a custom Comparator). Operations are
O(log n).
* *LinkedHashSet*: Maintains insertion order. Performance is slightly slower than HashSet due
to maintaining the linked list, but generally good.
*Common Set Methods:*
Let's consider Set<String> mySampleSet = new HashSet<>();
* mySampleSet.add("Element"); // Adds an element if it's not already present. Returns false if
duplicate.
* mySampleSet.remove("Element"); // Removes the speci ed element.
* boolean contains = mySampleSet.contains("Element"); // Checks if the set contains the
element.
* int size = mySampleSet.size(); // Returns the number of elements.
* boolean isEmpty = mySampleSet.isEmpty(); // Checks if the set has no elements.
* mySampleSet.clear(); // Removes all elements.
* Iterator<String> it = mySampleSet.iterator(); // Returns an iterator over the elements.
ff
ff
fi
### *3. Map Interface (Key-Value Pairs, Unique Keys)*
* *HashMap*: Stores key-value pairs. Optimized for fast lookups (average O(1)). No guaranteed
order.
Map<String, String> countryCapitals = new HashMap<>();
countryCapitals.put("USA", "Washington"); // Add key-value pair
countryCapitals.put("India", "Delhi");
String capital = countryCapitals.get("USA"); // Get value by key
countryCapitals.remove("India"); // Remove by key
// Output: {USA=Washington} (order not guaranteed)
* *TreeMap*: Stores key-value pairs, sorted by keys (natural order or custom Comparator).
Map<Integer, String> studentScores = new TreeMap<>();
studentScores.put(103, "Alice");
studentScores.put(101, "Bob");
studentScores.put(102, "Charlie");
String student = studentScores.get(101);
studentScores.remove(102);
// Output: {101=Bob, 103=Alice} (sorted by key)
* *LinkedHashMap*: Maintains insertion order of key-value pairs.
Map<String, Integer> productPrices = new LinkedHashMap<>();
productPrices.put("Laptop", 1200);
productPrices.put("Monitor", 300);
productPrices.put("Keyboard", 75);
Integer price = productPrices.get("Monitor");
productPrices.remove("Laptop");
// Output: {Monitor=300, Keyboard=75} (insertion order preserved)
*Di erences (Map):*
* *HashMap*: Fastest for put, get, remove (average O(1)). No iteration order guarantee. Allows
one null key and multiple null values.
* *TreeMap*: Keys are always sorted (natural order or custom comparator). Operations are O(log
n). Does not allow null keys.
* *LinkedHashMap*: Maintains insertion order (or access order, if con gured). Performance is
generally good, slightly slower than HashMap due to order maintenance. Allows one null key and
multiple null values.
*Common Map Methods:*
Let's consider Map<String, String> mySampleMap = new HashMap<>();
* mySampleMap.put("Key", "Value"); // Adds or updates a key-value pair.
* String value = mySampleMap.get("Key"); // Returns the value for a given key, or null.
* mySampleMap.remove("Key"); // Removes the key and its associated value.
* boolean containsKey = mySampleMap.containsKey("Key"); // Checks if the map contains the
speci ed key.
* boolean containsValue = mySampleMap.containsValue("Value"); // Checks if the map contains
the speci ed value.
* int size = mySampleMap.size(); // Returns the number of key-value mappings.
* boolean isEmpty = mySampleMap.isEmpty(); // Checks if the map has no key-value mappings.
* mySampleMap.clear(); // Removes all mappings.
* Set<String> keys = mySampleMap.keySet(); // Returns a Set view of the keys.
* Collection<String> values = mySampleMap.values(); // Returns a Collection view of the values.
ff
fi
fi
fi
* Set<Map.Entry<String, String>> entries = mySampleMap.entrySet(); // Returns a Set view of
the key-value pairs (Map.Entry objects).
-----