The Java Collections Framework provides a unified architecture for storing and manipulating groups of objects. It includes interfaces, implementations, and algorithms.
import java.util.*;
public classAdvancedCollectionsExample {
public static voidmain(String[] args) {
// Rotating elements
List<String> list = new ArrayList<>(
Arrays.asList("A", "B", "C", "D", "E")
);
Collections.rotate(list, 2);
System.out.println("Rotated by 2: " + list);
// Replacing elements
Collections.replaceAll(list, "A", "X");
System.out.println("After replacement: " + list);
// Filling
List<Integer> numbers = new ArrayList<>(Collections.nCopies(5, 0));
Collections.fill(numbers, 42);
System.out.println("Filled list: " + numbers);
// Disjoint check
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
List<Integer> list3 = Arrays.asList(3, 4, 5);
System.out.println("list1 and list2 disjoint: " +
Collections.disjoint(list1, list2));
System.out.println("list1 and list3 disjoint: " +
Collections.disjoint(list1, list3));
}
}
Interactive Collections Utilities Demo
Best Practices
Choose the Right Collection
Use ArrayList for random access
Use LinkedList for frequent insertions/deletions
Use HashSet for unique elements
Use TreeSet for sorted unique elements
Use HashMap for key-value lookups
Performance Tips
Initialize collections with capacity
Use primitive collections for better performance
Consider concurrent collections for thread safety
Use immutable collections when possible
Profile your code to find bottlenecks
Common Pitfalls
Modifying collections during iteration
Not implementing equals/hashCode properly
Using raw types instead of generics
Ignoring null handling
Not considering thread safety
Iterators in Java Collections
Iterator is an interface in Java used to traverse through the elements of a Collection. It provides methods to iterate, remove, and check existence of elements in a collection.
Basic Iterator Example
import java.util.*;
public classIteratorExample {
public static voidmain(String[] args) {
List<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Goat");
Iterator<String> iterator = animals.iterator();
// Traversing using while loopwhile (iterator.hasNext()) {
String animal = iterator.next();
System.out.println(animal);
}
}
}
Removing Elements Using Iterator
import java.util.*;
public classIteratorRemoveExample {
public static voidmain(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
Iterator<Integer> iterator = numbers.iterator();
// Removing even numberswhile (iterator.hasNext()) {
Integer num = iterator.next();
if (num % 2 == 0) {
iterator.remove();
}
}
System.out.println("After removal: " + numbers);
}
}