The Collections class in Java provides a set of utility methods for working with collections. These utility methods are helpful for performing common operations on collections and simplifying the code.
Some of the commonly used utility methods provided by the Collections class include:
sort()
: This method is used to sort the elements in a list in natural order or using a custom comparator.reverse()
: This method is used to reverse the order of elements in a list.shuffle()
: This method is used to randomly shuffle the elements in a list.binarySearch()
: This method is used to perform binary search on a list to find the index of a specified element.frequency()
: This method is used to find the frequency of a specified element in a list.
Here's an example that demonstrates the use of the Collections.sort()
method to sort an ArrayList of strings:
1import java.util.ArrayList;
2import java.util.Collections;
3
4public class Main {
5 public static void main(String[] args) {
6 // Create an ArrayList
7 ArrayList<String> fruits = new ArrayList<>();
8
9 // Add elements to the ArrayList
10 fruits.add("Apple");
11 fruits.add("Banana");
12 fruits.add("Orange");
13
14 System.out.println("Original ArrayList: " + fruits);
15
16 // Use the Collections class to sort the ArrayList
17 Collections.sort(fruits);
18
19 System.out.println("Sorted ArrayList: " + fruits);
20 }
21}
In the above code, we create an ArrayList
of strings and add some elements to it. We then use the Collections.sort()
method to sort the elements in the ArrayList
in natural order. Finally, we print the sorted ArrayList
to the console.
The Collections class provides many more utility methods that can be used for various operations on collections. Understanding and using these utility methods can greatly simplify working with collections in Java.
xxxxxxxxxx
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();
// Add elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Original ArrayList: " + fruits);
// Use the Collections class to sort the ArrayList
Collections.sort(fruits);
System.out.println("Sorted ArrayList: " + fruits);
}
}