HOME HTML EDITOR C JAVA PHP

Java Collections Methods

In Java, the Collections class provides useful static methods to operate on collection objects such as ArrayList, LinkedList, HashSet, etc.

The Collections class belongs to the java.util package. It contains methods for sorting, searching, reversing, shuffling, and more.

1. Importing Collections

import java.util.Collections; import java.util.ArrayList;

2. sort()

The sort() method sorts a collection in ascending order.

ArrayList numbers = new ArrayList(); numbers.add(5); numbers.add(1); numbers.add(8); Collections.sort(numbers); System.out.println(numbers);

3. reverse()

The reverse() method reverses the order of elements.

Collections.reverse(numbers); System.out.println(numbers);

4. shuffle()

The shuffle() method randomly changes the order of elements.

Collections.shuffle(numbers); System.out.println(numbers);

5. binarySearch()

The binarySearch() method searches for an element in a sorted list.

Collections.sort(numbers); int index = Collections.binarySearch(numbers, 5); System.out.println(index);

Important: The list must be sorted before using binarySearch().

6. max() and min()

The max() method returns the maximum element. The min() method returns the minimum element.

System.out.println(Collections.max(numbers)); System.out.println(Collections.min(numbers));

7. frequency()

The frequency() method counts how many times an element appears.

numbers.add(5); System.out.println(Collections.frequency(numbers, 5));

8. replaceAll()

The replaceAll() method replaces all occurrences of a value with another value.

Collections.replaceAll(numbers, 5, 10); System.out.println(numbers);

9. copy()

The copy() method copies elements from one list to another.

ArrayList newList = new ArrayList(); newList.add(0); newList.add(0); newList.add(0); Collections.copy(newList, numbers); System.out.println(newList);

10. fill()

The fill() method replaces all elements with a specified value.

Collections.fill(numbers, 100); System.out.println(numbers);

Why Collections Class is Important?

Difference Between Collection and Collections

Important Points

Conclusion

The Collections class provides powerful methods like sort(), reverse(), shuffle(), max(), min(), and more.

It makes working with collections easier and more efficient.

Tip: Always use Collections utility methods instead of writing long manual logic.