- Collection Framework in JavaCollections Class in JavaList Interface in Java with ExamplesArrayList in JavaVector Class in JavaLinkedList in JavaQueue Interface In JavaPriorityQueue in JavaSet in JavaHashSet in JavaLinkedHashSet in JavaMap in the JavaHashMap in JavaHashtable in JavaLinkedHashMap in Java
Collections Class in Java
The Collections
class is a utility class in Java that provides a set of methods for working with collections. It contains static methods that operate on or return collections, such as List
, Set
, and Map
, and provides a convenient way to perform common operations on these collections.
Here are some of the methods provided by the Collections
class:
sort()
: Sorts a list in natural order or using a specifiedComparator
.reverse()
: Reverses the order of elements in a list.shuffle()
: Shuffles the elements in a list.binarySearch()
: Searches for an element in a sorted list using binary search.max()
: Returns the maximum element in a collection.min()
: Returns the minimum element in a collection.unmodifiableList()
: Returns an unmodifiable view of a list.synchronizedList()
: Returns a synchronized view of a list.emptyList()
: Returns an empty list.singletonList()
: Returns a list containing a single element.
Here's an example of using the Collections
class to sort a list of integers:
import java.util.*;
public class SortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 9, 1, 7));
System.out.println("Before sorting: " + numbers);
Collections.sort(numbers);
System.out.println("After sorting: " + numbers);
}
}
In this example, we create an ArrayList
of integers and initialize it with a set of numbers. We then use the sort()
method provided by the Collections
class to sort the list in natural order, and print the result before and after sorting.
The Collections
class provides a convenient set of methods for working with collections in Java, and is a useful tool for performing common operations on collections in a concise and efficient manner.