Manipulating Lists with the Collections Class
The Java Collections framework provides a set of utility methods in the java.util.Collections
class that can be used to manipulate lists and other collection types. These methods offer a wide range of operations, such as sorting, shuffling, searching, and reversing elements within a collection.
Sorting Lists
One of the most common operations on lists is sorting. The Collections.sort()
method can be used to sort the elements of a list in ascending order. Here's an example:
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("LabEx");
myList.add("Java");
myList.add("Collections");
Collections.sort(myList);
System.out.println(myList);
}
}
When you run this code on an Ubuntu 22.04 system, it will output:
[Collections, Java, LabEx]
Reversing Lists
The Collections.reverse()
method can be used to reverse the order of elements in a list:
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("LabEx");
myList.add("Java");
myList.add("Collections");
Collections.reverse(myList);
System.out.println(myList);
}
}
This will output:
[Collections, Java, LabEx]
Searching Lists
The Collections.binarySearch()
method can be used to search for an element in a sorted list. It returns the index of the element if it is found, or a negative value if it is not found.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("LabEx");
myList.add("Java");
myList.add("Collections");
Collections.sort(myList);
int index = Collections.binarySearch(myList, "Java");
System.out.println("Index of 'Java': " + index);
}
}
This will output:
Index of 'Java': 1
By using the utility methods provided by the java.util.Collections
class, you can easily manipulate lists and other collection types in your Java applications.