Detailed explanation of Collections in Java

Detailed explanation of Collections in Java

In Java, java.util.Collectionsit is a utility class that provides various static methods for operating and controlling collections. This class contains many useful methods for sorting, searching, replacing, etc. operations on collections. The following is Collectionsa detailed explanation of some commonly used methods in classes:

1. Sorting

sort(List<T> list)

Used to Listsort a collection in ascending order. The elements in the sorted collection must implement Comparablethe interface or Comparatorperform a custom comparison via .

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
Collections.sort(numbers);
System.out.println("Sorted List: " + numbers);
reverse(List<?> list)

Used to reverse Listthe order of elements in .

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
Collections.reverse(names);
System.out.println("Reversed List: " + names);
shuffle(List<?> list)

Used to Listrandomly sort the elements in .

List<String> cards = Arrays.asList("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K");
Collections.shuffle(cards);
System.out.println("Shuffled List: " + cards);

2.Searching and Replacing

binarySearch(List<? extends Comparable<? super T>> list, T key)

ListUsed to find the specified element using a binary search algorithm in a sorted .

List<Integer> sortedList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int index = Collections.binarySearch(sortedList, 5);
System.out.println("Index of 5: " + index);
replaceAll(List<T> list, T oldVal, T newVal)

Used to Listreplace all occurrences of the specified element with a new element.

List<String> colors = new ArrayList<>(Arrays.asList("Red", "Green", "Blue", "Red", "Yellow"));
Collections.replaceAll(colors, "Red", "Orange");
System.out.println("List after replacement: " + colors);

3.Synchronization _

synchronizedList(List<T> list)

Returns a thread-safe one List.

List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
synchronizedMap(Map<K,V> map)

Returns a thread-safe one Map.

Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>());

These are just Collectionssome of the methods in the class. It also contains some other methods, such as min, max, copy, filletc., which can be selected and used according to specific needs. CollectionsThe class provides many practical utility methods to make working with collections more convenient and efficient.

Guess you like

Origin blog.csdn.net/wykqh/article/details/135144261