collection

Java Collectors toMap

Use the Java Collections Framework

Collect Synchronized

Collections.synchronizedList(List<T>) – this method is used to make a list thread-safe by synchronizing it.

A Queue is not synchronized by default. 
But you can use a ConcurrentLinkedQueue or a BlockingQueue implementation for achieving thread safety.

A Map is not synchronized by default. 
But you can use Collections.synchronizedMap() or ConcurrentHashMap implementations for achieving thread safety.


1.Sorting: Collections.sort(List<T>) – this method is used to sort the elements of a list in ascending order.

2.Searching: Collections.binarySearch(List<T>, key) – this method is used to search for a specific element in a sorted list and return its index.

3.Reverse order: Collections.reverse(List<T>) – this method is used to reverse the order of elements in a list.

4.Min/Max Operations: Collections.min(Collection<T>) and Collections.max(Collection<T>) – these methods are used to find the minimum and maximum elements in a collection, respectively.

5.Synchronization: Collections.synchronizedList(List<T>) – this method is used to make a list thread-safe by synchronizing it.

6.Unmodifiable Collections: Collections.unmodifiableList(List<T>) – this method is used to create a read-only view of a list, preventing modifications.


不可变集合
Collections还提供了一组方法把可变集合封装成不可变集合:

封装成不可变List:List<T> unmodifiableList(List<? extends T> list)
封装成不可变Set:Set<T> unmodifiableSet(Set<? extends T> set)
封装成不可变Map:Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m)
这种封装实际上是通过创建一个代理对象,拦截掉所有修改方法实现的

线程安全集合
Collections还提供了一组方法,可以把线程不安全的集合变为线程安全的集合:

变为线程安全的List:List<T> synchronizedList(List<T> list)
变为线程安全的Set:Set<T> synchronizedSet(Set<T> s)
变为线程安全的Map:Map<K,V> synchronizedMap(Map<K,V> m)