predefined algorithms for Collection class in Java
The java.util.Collections
class is a utility class that provides a number of predefined algorithms for working with collections in Java. Here is a list of the algorithms provided by the Collections
class:
addAll()
: Adds all the elements of one collection to another.binarySearch()
: Searches for a specified element in a sorted list using a binary search algorithm.copy()
: Copies elements from one list to another.disjoint()
: Returnstrue
if two collections have no elements in common.fill()
: Fills a list with a specified element.indexOfSubList()
andlastIndexOfSubList()
: Returns the index of the first or last occurrence of a sublist within a list.max()
andmin()
: Returns the maximum or minimum element in a collection according to their natural order or using a custom comparator.nCopies()
: Returns a list containing a specified number of copies of a specified object.reverse()
: Reverses the order of the elements in a list.rotate()
: Rotates the elements in a list by a specified distance.shuffle()
: Shuffles the elements of a list randomly.sort()
: Sorts the elements of a list according to their natural order or using a custom comparator.swap()
: Swaps the elements at two specified positions in a list.
Here is an example of how you might use some of the algorithms provided by the java.util.Collections
class:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(7);
numbers.add(1);
numbers.add(3);
// Create a second list of integers
List<Integer> moreNumbers = new ArrayList<>();
moreNumbers.add(6);
moreNumbers.add(4);
moreNumbers.add(8);
// Add all the elements from the second list to the first list
boolean changed = Collections.addAll(numbers, 6, 4, 8);
System.out.println(changed); // true
System.out.println(numbers); // [5, 2, 7, 1, 3, 6, 4, 8]
// Sort the list
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 3, 4, 5, 6, 7, 8]
// Search for an element in the list using a binary search
int index = Collections.binarySearch(numbers, 5);
System.out.println(index); // 4
// Reverse the list
Collections.reverse(numbers);
System.out.println(numbers); // [8, 7, 6, 5, 4, 3, 2, 1]
// Shuffle the list
Collections.shuffle(numbers);
System.out.println(numbers); // [1, 5, 8, 3, 6, 4, 7, 2] (example)
// Fill the list with a specific value
Collections.fill(numbers, 0);
System.out.println(numbers); // [0, 0, 0, 0, 0, 0, 0, 0]
// Get the minimum and maximum element in the list
int min = Collections.min(numbers);
int max = Collections.max(numbers);
System.out.println(min); // 0
System.out.println(max); // 0
// Create a list of copies of a specific object
List<String> words = Collections.nCopies(3, "hello");
System.out.println(words); // [hello, hello, hello]
}
}