Using TreeSet to realize two sorting methods of Comparable and Comparator (NATURAL sorting and customized sorting)

Recently, I was looking at the relevant contents of collections in Javase. As one of the implementation classes of the Set interface, TreeSet adopts the storage structure of red black tree.
The requirements are:
1) Attributes added to TreeSet must be objects of the same class;
2) Every time you insert elements into the tree through add (), you need to compare (comparato() or compare()) to ensure that the same elements are not inserted into the tree species; This is different from other implementation classes of the Set interface, because the data stored in the Set is unordered and non repeatable. Therefore, when calling add() to perform the insertion operation, the size must be compared, but the other two implementation classes of the Set interface HashSet and LinkedHashSet use the rewritten equals() in the class corresponding to the object to be inserted
3) Note: in terms of comparing the size of inserted elements, here (TreeSet) is different from other implementation classes of the Set interface. Because the data stored in Set is unordered and non repeatable, it is necessary to compare the size when calling add() for insertion, except that the other two implementation classes of the Set interface HashSet LinkedHashSet uses the rewritten equals() in the class corresponding to the object to be inserted

Title:

Create five employee objects and put them into the tree set
*The elements are sorted according to the following two docking methods:
1) Make the employee implement the comparable interface and sort according to the
(first create a treeset, add elements with add (), and then write a comparato(), because in treeset, comparato() is essentially used for comparison)
2) When creating a treeset, pass in a com object (using a constructor with formal parameters) and sort it according to the order of birthday date

Code implementation:

1) Employee class:

public class Employee implements Comparable{

	private String name;
	private int age;
	private MyDate birthday;
	//constructor 
	public Employee(String name, int age, MyDate birthday) {
		super();
		this.name = name;
		this.age = age;
		this.birthday = birthday;
	}
	public Employee() {
		super();
	}
	//get and set methods
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public MyDate getBirthday() {
		return birthday;
	}
	public void setBirthday(MyDate birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "Employee [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
		//birthday here calls mydate and its own toString
	}
	
	//In the order of names
	@Override
	public int compareTo(Object o) {
		
		if(o instanceof Employee) {
			//First strong turn
			Employee e = (Employee) o;
			//Compare sizes and return
			//From small to large by name
			return this.name.compareTo(e.name);
		}
		//Using return 0, you can also:
		//Because the same data cannot be placed in the treeset, return 0 means the same data -------- -- > cannot be placed in the tree
		return 0;
	}
}

2) MyDate class:

public class MyDate implements Comparable {

	private int year;
	private int month;
	private int day;

	// constructor 
	public MyDate() {
		super();
	}

	public MyDate(int year, int month, int day) {
		super();
		this.year = year;
		this.month = month;
		this.day = day;
	}

	// get and set methods
	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	@Override
	public String toString() {
		return "MyDate [year=" + year + ", month=" + month + ", day=" + day + "]";
	}

	//Under the cloak of natural sorting, it is actually part of the implementation of custom sorting in the employeetest class
	@Override
	public int compareTo(Object o) {

		if (o instanceof MyDate) {
			MyDate m = (MyDate) o;

			// Compare years first
			int minusYear = this.getYear() - m.getYear();
			if (minusYear != 0) {
				// Different year
				return minusYear;
			}
			// Same year
			int minusMonth = this.getMonth() - m.getMonth();
			if (minusMonth != 0) {
				// Different months
				return minusMonth;
			}
			// The same goes for months

			// The logic of comparing dates can also be written as:
			return this.getDay() - m.getDay();
		}

		return 0;
	}

}

3) EmployeeTest class:

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

import org.junit.Test;

public class EmployeeTest {
	// Question 1: use natural sorting
	@Test
	public void test1() {
		TreeSet set = new TreeSet();

		Employee e1 = new Employee("liudehua", 55, new MyDate(1965, 5, 4));
		Employee e2 = new Employee("zhangxueyou", 43, new MyDate(1987, 5, 4));
		Employee e3 = new Employee("guofucheng", 44, new MyDate(1987, 5, 4));
		Employee e4 = new Employee("liming", 51, new MyDate(1954, 8, 1));
		Employee e5 = new Employee("liangchaowei", 21, new MyDate(1978, 12, 4));
		/*
		 * If the Chinese name is in the order of UTF-8, it may produce: similar to -- Liming is behind Zhang Xueyou.
		 * ----However, in the mobile phone address book, there will be no such situation: because it is not compared according to the value in UTF-8 corresponding to Chinese characters; Instead, first find the Pinyin corresponding to Chinese characters, and then compare them according to Pinyin
		 */

		set.add(e1);
		set.add(e2);
		set.add(e3);
		set.add(e4);
		set.add(e5);
		/*
		 * treeset If it is required to put the data, use the red black tree to put it, ----- > actually: compare the size first, and then put the data
		 */
		// output
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

	// Question 2: sort by birthday:
	@SuppressWarnings("unchecked")
	@Test
	public void test2() {

		//At this time, the constructor of treeset should choose the constructor with parameters -- the anonymous object of the anonymous implementation class is adopted, because it is used here once (it is convenient to write in this way)
		
		TreeSet set = new TreeSet(new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				if(o1 instanceof Employee && o2 instanceof Employee) {
					Employee e1 = (Employee) o1;
					Employee e2 = (Employee) o2;
					
					//Note: the date class of dates can also be sorted naturally by default. It is considered that the smaller the number is, the smaller the number is
					MyDate b1 = e1.getBirthday();
					MyDate b2 = e2.getBirthday();
//					
					//Method 1: write the logic of comparing mydate in the anonymous object of the anonymous implementation class of comparable
//					//Compare years first
//					int minusYear = b1.getYear() - b2.getYear();
//					if(minusYear != 0) {
//						//Different year
//						return minusYear;
//					}
//					//Same year
//					int minusMonth = b1.getMonth()- b2.getMonth();
//					if(minusMonth != 0) {
//						//Different months
//						return minusMonth;
//					}
//					//The same goes for months
//					
					int minusDay = b1.getDay() - b2.getDay();
					if(minusDay != 0) {
						//If the date is different
						return minusDay;
					}else {
						//The date is the same
						return 0;
					}
//					//The logic of comparing dates can also be written as:
//					return b1.getDay() - b2.getDay();
					
					
					//Method 2: write the comparison of mydate in the mydate class
					/*
					 * Let mydate implement comparable,
					 * Rewrite comparato() in mydate
					 * Here (in the compare method overridden in the anonymous object of the anonymous implementation class of the comparator),
					 * Call the rewritten comparato () in mydate
					 */
					//Manually implement the override of compareto() in mydate class so that it can be called directly here
					return b1.compareTo(b2);
					
					
				}
				
				return 0;

			}
			
		});

		Employee e1 = new Employee("liudehua", 55, new MyDate(1965, 5, 4));
		Employee e2 = new Employee("zhangxueyou", 43, new MyDate(1987, 5, 4));
		Employee e3 = new Employee("guofucheng", 44, new MyDate(1987, 5, 4));
		Employee e4 = new Employee("liming", 51, new MyDate(1954, 8, 1));
		Employee e5 = new Employee("liangchaowei", 21, new MyDate(1978, 12, 4));
		/*
		 * If the Chinese name is in the order of UTF-8, it may produce: similar to -- Liming is behind Zhang Xueyou.
		 * ----However, in the mobile phone address book, there will be no such situation: because it is not compared according to the value in UTF-8 corresponding to Chinese characters; Instead, first find the Pinyin corresponding to Chinese characters, and then compare them according to Pinyin
		 */

		set.add(e1);
		set.add(e2);
		set.add(e3);
		set.add(e4);
		set.add(e5);
		/*
		 * treeset If it is required to put the data, use the red black tree to put it, ----- > actually: compare the size first, and then put the data
		 */
		// output
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

}


Never lose your original self
----Don't forget your original heart, you can always.

Keywords: Java

Added by me102 on Sat, 19 Feb 2022 06:24:35 +0200