Java Iterators and Comparators
Iterators provide a way to access elements of a collection sequentially. Comparators allow custom sorting of elements in a collection.
Using Iterators with ArrayList:
// Example of using Iterator with ArrayList
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorExample {
public static void main(String[] args) {
// Creating an ArrayList
List<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Using Iterator to traverse the list
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}
}
}
Using Comparators with TreeSet:
// Example of using Comparator with TreeSet
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class ComparatorExample {
public static void main(String[] args) {
// Creating a TreeSet with a custom comparator
Set<String> colors = new TreeSet<>(Comparator.reverseOrder());
// Adding elements
colors.add("Red");
colors.add("Green");
colors.add("Blue");
// Accessing elements (sorted in reverse order)
System.out.println("Colors: " + colors);
}
}
Note:
Iterators provide a way to traverse elements of a collection sequentially. Comparators allow custom sorting of elements, providing flexibility in ordering. These concepts are often used with various collection types in Java.