Set Framework and Corresponding Applications

Keywords: Java Lambda

Collective Framework

Brainstorming mind mapping

Preliminary conditions:

When writing an object-oriented program, a group of objects of the same type are often used, and arrays can satisfy it. But the disadvantage of arrays is that once defined, they cannot be changed in size.

The concept of set:

A collection is an object used to store a set of objects. Collections are comparable to a container, providing ways to save, retrieve, and manipulate other elements
Set is the combination of several similar "data" for the same purpose into a whole.

Collections are systematically divided into three types:

(1) List: The order of elements, allowing the same elements to be included. -------------------
(2) Set: It does not distinguish the order of elements and does not allow the same elements to be included.
(3) Map: Map set saved key - "value" pair, "key" can not be repeated, and a "key" can only correspond to a "value".
Java collections can only store reference data types, that is, the address of the object, not the object itself. Elements in a collection correspond to variables of reference type.

ArrayList class

Prerequisite: It is the most commonly used class of linear table implementations, set objects implemented through arrays

A Construction Method

ArrayList () - - Creates an empty array linear table object with a default initial capacity of 10.
ArrayList (Collection c) - Creates an array linear table object with elements in set C.
ArrayList (int initial capacity) - - Creates an empty array linear table object and specifies the initial capacity. -

Second application

package four iterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ArraysList {
	public static void main(String[] args) {
//		Create an object of ArraysList with the specified object type String
		List <String> pets = new ArrayList<String>();
//		Add the corresponding object to the array
		pets.add("cat");
		pets.add("dog");
		pets.add("turtle");
//		Traversing arrays using enhanced for loops
		for(String p:pets) {
			System.out.print(p+"  ");
		}
//		Declare and assign an array of String types with two elements directly
		String [] bigp= {"tiger","monkey"};
//		Create a collection collection collection
		Collection<String> coll = new ArrayList<>();
//		Add array elements of String type to Collection collection
		coll.add(bigp[0]);
		coll.add(bigp[1]);
//		Adding elements of coll array to pets collection using addAll method
		pets.addAll(coll);//Add new elements to the end of the linear table
		System.out.println();
		System.out.println(pets);
//		Create an iterator object by iterating through all elements in the pets array with an iterator
		Iterator <String>iter = pets.iterator();
		while(iter.hasNext()) {//Judging whether there are still objects
			String p = iter.next();//Determine if there is another object
			System.out.print(p+"  ");
		}
	}
    }
    //Implementation results:
    cat  dog  turtle  
[cat, dog, turtle, tiger, monkey]
cat  dog  turtle  tiger  monkey  

Application 2:

package four iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
// Application of Bidirectional Iterator
public class DerectionIteratorDemo {
	public static void main(String[] args) {
// Create an ArrayList object
		List<String> myLi = new ArrayList<String>();
		myLi.add("How are you?");
		myLi.add("I'm fine. "";
		myLi.add("I'm gone! "";
		myLi.add("don't read (--)");
// Create ListIterator objects
		ListIterator<String> iter = myLi.listIterator();
// Move the iterator pointer to the end of the linear table
		While (iter. hasNext (){// Is there another element
			iter.next();// Returns the next element
		}
// Access each element of the linear table from back to front
		while(iter.hasPrevious()) {// Is there a previous element
			System.out.print(iter.previous()+";// Returns the previous element
		}
	}
}

Initial length of set: 0
 Length 1 after adding elements
2
 Set Length after Secondary Addition: 2
 The length after removal is 0:
true
 Big fish
185

set

HashSet and TreeSet

package one.collection.Interface;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class hasd {
	public static void main(String[] args) {
		Set<String> type = new HashSet<String>();//hashset has the best access performance, but the elements have no order
		type.add("Blue rose");
		type.add("White Rose");
		type.add("peony");
		type.add("peony");
		System.out.println(type);//As a result, duplicate elements cannot be added to the collection when adding elements to the set object
		
		Set<String> s = new TreeSet<String>();//Elements in TreeSet will be sorted automatically
		String[] num = new String[] {"hare","panda","fish","cat"};
		for(int i=0;i<num.length;i++) {//Traversing array elements using for loops
			s.add(num[i]);//Adding array elements to TreeSet objects
		}
		System.out.println("Natural sequential comparison output:"+s);	
//		If the comparator object is not specified when creating the TreeSet object, the elements in the collection are arranged in natural order.
//		The second sort method is to specify a comparator object when creating a TreeSet object. For example, implement descending sort of strings
//		Following the above TreeSet code
//		Using Lambda Expressions to Realize String Inversion
		s=new TreeSet<>((String num1,String num2)->num2.compareTo(num1));
		for(int i=0;i<num.length;i++) {//Traversing array elements using for loops
			s.add(num[i]);//Adding array elements to TreeSet objects
		}
		System.out.println("Custom reverse order:"+s);
	}
}
[Blue rose, peony, White Rose]
//Natural sequential comparison output: [cat, fish, hare, panda]
//Custom inversion: [panda, hare, fish, cat]

Map

HashMap

package one.aggregate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMap1 {
	public static void main(String[] args) {
		String[]country= {"China","India","Australia","Germany","Cuba","Greece","Japan"};
		String[]capital= {"Bejing","New Delhi","Canbella","Berlin","Havana","Athens","Tokyo"};
//		Running HashMap Object
		Map<String,String> mp = new HashMap<>();
		for(int i=0;i<country.length;i++) {
			mp.put(country[i], capital[i]);
		}
		System.out.println("Share:"+mp.size()+"Country");
		System.out.println(mp);
		System.out.println(mp.get("China"));
		mp.remove("Japan");
		Set<String> co = mp.keySet();
		for(Object c:co) {
			System.out.print(c+" ");
		}
	}
}
//Total: 7 countries
{Greece=Athens, Cuba=Havana, China=Bejing, Japan=Tokyo, Australia=Canbella, Germany=Berlin, India=New Delhi}
Bejing
Greece Cuba China Australia Germany India0

TreeMap

TreeMap

package one.aggregate;
//Read data from a text and count the number of different prosperous words and the number of occurrences of each word in the document.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
public class TreeMap1 {
	public static void main(String[] args) throws FileNotFoundException  {
//		Declare variables
		String line = null;
		String [] words = null;
//		The key/value pair in TreeMap is the order in which keys are stored in TreeMap. The order of keys is alphabetical
		Map <String,Integer> m =new TreeMap<>();
//		Create File Input Stream
		BufferedReader br = new BufferedReader(new FileReader("D:\\WeSingCache\\WeSingDL\\Temp\\CdnRace\\English.txt")); 
			try {
				while((line = br.readLine())!=null) {//The condition of the loop is that the number of rows read cannot be empty
					words = line.split("[, .]");//Read one line at a time and parse it into an array of strings
					for(String w:words) {
						Integer count =m.get(w);//Returns the number of words
						if(count==null) {//Represents that w is not in m
							m.put(w, 1);
						}else {
							m.put(w,count+1);
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		System.out.println("Share:"+m.size()+"A different word");
		System.out.println(m);
	}
} 
    //Total: 13 different words
{a=1, begun=1, done=1, gain=1, half=1, is=3, no=2, pain=1, there=2, way=1, well=1, where=1, will=1}

threeMap,HashMap and Hashtable

package one.aggregate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapDemo02 {
	public static void main(String[] args) {	
		//The generic type of HashMap map set is that the type of key must be integer 
		//The value type must be String
		Map<Integer, String>  m = new HashMap();
		System.out.println("**********First***********************");
		Map m1 = new HashMap();
		//Add the element put to the collection except that it is asynchronous and allows null values
		m1.put("aa", "Zhang San");
		m1.put("oo", "Li Si");
		m1.put("33", "Wang Wu");
		m1.put(null, "Wang Wu");
		System.out.println(m1);
		System.out.println("***************The second******************");
		//key cannot be null   
		Map m2 = new TreeMap();
		m2.put("oo", "Li Si");
		m2.put("ww", "Wang Wu");
		m2.put("33" ,null);
		System.out.println(m2);
		System.out.println("*************Third********************");
		//Neither the value of key nor the value of value can be null
		Map m3= new Hashtable();
		m3.put("oo", "Li Si");
		m3.put("ww", "wangw");
		//When does the program go wrong?
		try {
			m3.put("33" ,200);
		} catch (Exception e) {
			System.out.println("There's a problem here.");
		}
		
//		System.out.println(m3);
		m3.replace("ww", "wangw", 100);
		System.out.println(m3);
		
	}

 **********First***********************
{aa=Zhang San, oo=Li Si, 33=Wang Wu, null=Wang Wu}
***************The second******************
{33=null, oo=Li Si, ww=Wang Wu}
*************Third********************
{oo=Li Si, 33=200, ww=100}

Iterator

Usage of ordinary iterators

package four iterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
//Collections can store arbitrary types of objects
//When no generic type is used to specify the type of data stored in a collection, the collection stores everything.
public class Transition of Iterator {
	public static void main(String[] args) {
//		Create collection of collections
		Collection coll = new ArrayList();
		coll.add("a");
		coll.add("b");
		coll.add("c");
		coll.add("d");
//		Obtaining iterators
		Iterator it = coll.iterator();
		while (it.hasNext()) {
//			Object when it.Next() gets the object data type
			Object obj = it.next();
//		When you need to use subclass object-specific methods, you need to transition down
			String str = (String) it.next();
			System.out.println(str.length());
//Note: If there are multiple objects in the collection, type conversion exceptions will occur when the downward transition is made.
			}
	}
}
1
1

Use of bidirectional iterators

package four iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
//Application of Bidirectional Iterator
public class DerectionIteratorDemo {
	public static void main(String[] args) {
//		Create an ArrayList object
		List<String> myLi = new ArrayList<String>();
		myLi.add("How are you?");
		myLi.add("I'm fine");
		myLi.add("I'm leaving!");
		myLi.add("Don't read(--)");
//		Create ListIterator objects
		ListIterator<String> iter = myLi.listIterator();
//		Move the iterator pointer to the end of the linear table
		while(iter.hasNext()) {//Is there the next element?
			iter.next();//Return to the next element
		}
//		Access each element of the linear table from back to front
		while(iter.hasPrevious()) {//Is there a previous element?
			System.out.print(iter.previous()+" ");//Returns the previous element
		}
	}
}
//Result:
//Don't read (--) I'm gone! I'm fine. How are you? 

Collections Tool Class

sort

BiarySearch Method - --- Search and Sort

package one.aggregate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
// The binarySearch() method finds the specified element in the sorted list
public class binarySearch1 {
	public static void main(String[] args) {
//		The aslist () method in the Array class - ----------------------------------------------------------------------------------------------------------------------------
		List<Integer> li = Arrays.asList(1,15,13,27);
		Collections.sort(li);//Sort in ascending order in natural order. Only after ascending order can binary Search be used for searching.
		System.out.println(li);
		Integer key=4;
//		Find in li by key
		int p = Collections.binarySearch(li, key);
		if(p<0) {//Key/value does not exist
//			Pass li as a parameter to the following List constructor
			List<Integer> li1 = new ArrayList<>(li);
//			If found, the method returns the element subscript, otherwise it returns (- insertion point - 1), where the element should be inserted into the subscript position in the list.
			li1.add(-p-1,key);
			System.out.println(li1);
		}
	}
}
[1, 13, 15, 27]
[1, 4, 13, 15, 27]

shuffle method - ------------------- disruption of order

package one.aggregate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
//shuffle() method can disrupt the order of elements
public class shuffleMeans {
	public static void main(String[] args) {
		Integer[]num = {1,15,81,13,57,46,26};
		List<Integer>list=Arrays.asList(num);
		System.out.println("The order after insertion:"+list);
		Collections.sort(list);
		System.out.println("The order after sorting:"+list);
		Collections.shuffle(list, new Random());
		System.out.println("After disrupting the order"+list);
	}

}
//The order after insertion: [1, 15, 81, 13, 57, 46, 26]
//The order after sorting: [1, 13, 15, 26, 46, 57, 81]
//After disruption [13, 81, 57, 15, 1, 26, 46]

Posted by kathas on Sun, 18 Aug 2019 03:24:58 -0700