Collection tool class collection code details

Sketch

Collections: a tool class for manipulating sets, lists, maps and other collections, mainly including methods for sorting, querying, modifying, setting immutability, and synchronization control of elements.


Sort operation

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

public class sortedTest {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>();
		list.add(0);
		list.add(19);
		list.add(23);
		list.add(-2);
		System.out.println("Normal output:"+list);
		//Reverses the order of elements in the specified list collection
		Collections.reverse(list);
		System.out.println("Reverse output:"+list);
		//Ascending sort
		Collections.sort(list);
		System.out.println("Ascending output:"+list);
		//Random order, shuffle
		Collections.shuffle(list);
		System.out.println("Shuffle at random:"+list);
		//Exchange elements at i and j
		Collections.swap(list, 0, 3);
		System.out.println("Exchange output:"+list);
		//N is a positive number, the last n elements move to the front, n is a negative number, and the first n elements move to the back
		Collections.rotate(list, 2);
		System.out.println("Forward output:"+list);
		//Comparator sort, descending
		Collections.sort(list, (o1,o2)->{
			return (Integer)o1>(Integer)o2?-1:(Integer)o1<(Integer)o2?1:0;
		});
		System.out.println("Output in descending order:"+list);
	}
	
}

Find, replace

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

public class searchTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<Integer> numbers = new ArrayList<>();
		numbers.add(0);
		numbers.add(2);
		numbers.add(23);
		numbers.add(-9);
		numbers.add(2);
		numbers.add(2);
		System.out.println(numbers);
		//Natural ordering by element
		System.err.println("Maximum element:" + Collections.max(numbers));
		System.err.println("Minimum element:" + Collections.min(numbers));
		//The number of occurrences of the specified element in the collection
		System.out.println("2 stay numbers Number of occurrences in:" + Collections.frequency(numbers, 2));
		//Replace all 2 in numbers with 12
		Collections.replaceAll(numbers, 2, 12);
		System.out.println("Replace with 12 numbers All 2 in: "+numbers);
		//Binary search can only be used when the elements in numbers are in an ordered state
		Collections.sort(numbers);
		System.out.println("sort: "+numbers);
		System.out.println("23 stay numbers Index in: "+Collections.binarySearch(numbers, 23));
	}

}

Synchronous control

In the Collections class, multiple synchronizedXxx() methods are provided to wrap the specified collection into a collection of thread synchronization, so as to solve the thread safety problem when multiple threads access the collection concurrently.
//Thread safe collection object, passing the newly created collection object directly to the synchronizedXxx() method of Collections
        
Collection c = Collections.synchronizedCollection(new ArrayList());
List list = Collections.synchronizedList(new arrayList());
Set s = Collections.synchronizedSet(new HashSet());
Map m = Collections.synchronizedMap(new HashMap());

Similar to Vector, use Hashtable as little as possible. Even if you need to create a thread safe Map implementation class, you can use the Collections tool class to turn HashMap into thread safe.
How to use Collections tool class to make HashMap thread safe?
Map m = Collections.synchronizedMap(new HashMap())

Set immutable set

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/*Set immutable collection, only accessible, not modifiable
 * Collections.emptyXxx():Returns an empty and immutable Set, which can be List, Map, SortedMap, Set, SortedSet
 * singletonXxx(): Returns an immutable collection containing only specified objects, which can be List or Map.
 * unmodifiableXxx():Returns the immutable view of the collection object, which can be List, Map, SortedMap, Set, SortedSet
 *   The program can directly call the of() method of Set, List and Map to create an immutable Set containing N elements.
 * */

public class unmodifiableCollections {
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//Returns an empty, immutable collection
		List emptyList = Collections.EMPTY_LIST;
		
		//Returns an immutable collection containing only the specified object
		Set singletonSet = Collections.singleton("Hello");
		
		//Common Map set
		Map scores = new HashMap();
		scores.put("Chinese", 87);
		scores.put("Mathematics", 97);
		//Returns an immutable view of a collection object
		Map unmodifiableMap = Collections.unmodifiableMap(scores);
		
		//Create a Set set with three elements
		Set set = Set.of("Python","Java","Qt");
		
		//Create a List of 4 elements
		List list = List.of(1,2,3,4);
		
		//Create a Map set containing three key value pairs
		Map map = Map.of("Chinese",98,"Mathematics",97,"English?",90);
		Map map1 = Map.ofEntries(Map.entry("Chinese", 98),Map.entry("Mathematics", 97),Map.entry("English?", 97));
		
		System.out.println(emptyList);			//[]
		System.out.println(unmodifiableMap);	//{mathematics = 97, {Chinese = 87}
		System.out.println(singletonSet);		//[Hello]
		
		System.out.println(list);				//[1, 2, 3, 4]
		System.out.println(set);				//[Python, Java, Qt]
		System.out.println(map);				//{English = 90, {mathematics = 97,} Chinese = 98}
		System.out.println(map1); 				//{mathematics = 97, {English = 97,} Chinese = 98}
	}
}


Keywords: Java Python Qt

Added by ziesje on Mon, 28 Oct 2019 18:41:10 +0200