Collections in Java
Collections in Java
Introduction to Collections
add(E e): Adds the specified element to the set if it is not already present.
remove(Object o): Removes the specified element from the set.
contains(Object o): Checks if the set contains the specified element.
size(): Returns the number of elements in the set.
clear(): Removes all elements from the set.
isEmpty(): Checks if the set is empty.
iterator(): Returns an iterator over the elements in the order they were
inserted.
TreeSet
It uses a red-black tree internally to store elements, ensuring that the set is
sorted in natural order.
Key Features of TreeSet:
Sorted Order: Elements are stored in ascending order by default. You can
provide a custom comparator for a different sorting order.
No Duplicates: Like all sets, TreeSet does not allow duplicate elements.
Efficient Performance: Basic operations like add, remove, and contains
have a time complexity of O(log n) due to the underlying tree structure.
TreeSet: Methods
first(): Returns the first (lowest) element in the set.
last(): Returns the last (highest) element in the set.
ceiling(E e): Returns the smallest element greater than or equal to the given
element, or null if none exists.
floor(E e): Returns the largest element less than or equal to the given element,
or null if none exists.
higher(E e): Returns the smallest element strictly greater than the given
element, or null.
lower(E e): Returns the largest element strictly less than the given element, or
null.
subSet(E fromElement, E toElement): Returns a view of the portion of the set
within the given range.
headSet(E toElement): Returns a view of the portion of the set strictly less than
the given element.
tailSet(E fromElement): Returns a view of the portion of the set greater than or
equal to the given element.
LinkedHashSet
add(E e): Adds the specified element to the set if it is not already present.
remove(Object o): Removes the specified element from the set.
contains(Object o): Checks if the set contains the specified element.
size(): Returns the number of elements in the set.
clear(): Removes all elements from the set.
isEmpty(): Checks if the set is empty.
iterator(): Returns an iterator over the elements in the order they were
inserted.
Summary
Java Collections Framework simplifies the handling of data
structures.
It provides a wide range of interfaces and classes.
Choosing the right collection depends on the use case.
Collections improve code maintainability and efficiency.