Class relations: + java.lang.Object + - java.util.Collections
This class is a member of Java Collections Framework.
This class is a utility class that contains exclusively of static methods that operate on or return Java collections like sorting, searching, and modifying elements within a collection.
Collections methods
addAll()
The add all method adds all of the specified elements or collection to a target collection. It is useful when combining two collections or copy elements from one collection to another.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
boolean b = Collections.addAll(set, 1, 2, 3, 4, 5);
System.out.println("Boolean result:" + b);
System.out.println(set);
}
}
[1, 2, 3, 4, 5]
sort()
This method works with lists of any type T
that extends Comparable <? super T>
. Which is the element of the list must implement the comparable interface to themselves or any of their super class. (More about generics in Generics)
import java.util.*;
class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
// Define natural ordering for Person objects
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// Sort by age using the natural ordering
Collections.sort(people);
System.out.println(people);
}
}
The sort method can also take a Comparator as an argument. This allows you to define a custom ordering for elements in a list. The method signature for this variation is:
public static <T> void sort(List<T> list, Comparator<? super T> c)
More about sorting with comparator in Comparator Interface.
Back to parent page: Java Standard Edition (Java SE) and Java Programming