Natural and customized sorting of TreeSet

Keywords: less Java

Natural and customized sorting of TreeSet

TreeSet is an ordered set
TreeSet supports two sorting methods, natural sorting and custom sorting. The default is natural sorting
TreeSet: the data structure of red black tree is used in the bottom layer. Red black tree is a specific type of binary tree, with the rule of left small and right large. If the elements have the characteristics of natural order, they are sorted and stored according to the natural order of the elements. Natural order: 1234, abcd, etc
TreeSet notes:
1. When adding elements to TreeSet, if the elements themselves have the characteristics of natural order, they will be stored according to the natural order characteristics of the elements themselves;
2. If the element itself does not have the characteristics of natural order, the class to which the element belongs must implement the compatible interface, rewrite the compareTo() method, and define the compareTo() method on the element's comparison rules;
3. If the compareTo() method returns 0 when comparing elements, the element is regarded as a duplicate element and cannot be added;
Out of order: the order of adding and removing elements is inconsistent

Natural order:

public class Person implements Comparable {
	private String name;

	private int age;

	public Person() {
		super();
	}

	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;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	
	// This method is called by TreeSet and does not need to be called by ourselves;
	@Override
	public int compareTo(Object o) {
		// The natural order of defining Person type is: sort by age, and sort by name for the same age
		
		if (!(o instanceof Person)) {
			throw new ClassCastException("error in type");
		}
		Person p = (Person) o;
		// Two elements are compared:
		System.out.println(this.name + " compare " + p.name);
		// Negative, 0, and positive numbers respectively indicate that the current object is less than, equal to, and greater than the specified object; negative reverse order
		System.out.println(this.age);
		System.out.println(p.age);
		return  p.age-this.age;
	}
}

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

public class TreeSetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet<Person> ts = new TreeSet<Person>();
		ts.add(new Person("Zhang San", 23));
		ts.add(new Person("Li Si", 22));
		ts.add(new Person("Wang Wu", 28));
		ts.add(new Person("Niu six", 36));
		ts.add(new Person("Xie Qi", 30));

		Iterator<Person> it = ts.iterator();
		
		while (it.hasNext()) {
			Person p = (Person) it.next();
			System.out.println(p.getName() + ":" + p.getAge());
		}
	}
}

Custom sort:
TreeSet notes:
4. If when adding elements to the TreeSet collection, the elements themselves do not have the characteristics of natural order, and the class to which the elements belong does not implement the Comparable interface, then a comparer must be passed in when creating TreeSet objects;
Customize the format of Comparator: define a class to implement the Comparator interface, and implement the compare() method. Define the comparison rules between elements in the compare() method;
Two methods of custom element comparison rules: implementing the Comparable interface and implementing the Comparator interface (Comparator);
Recommended use: comparator;
Because of the class that implements the compatible interface, the comparison rules can only be used in the current class;
The self-defined comparator can define the comparison rules for any class, and has good reusability;
5. If the comparison rules of Comparable and Comparator are defined, the comparison rules of Comparator are preferred;
TreeSet can sort strings directly, because string has implemented the compatible interface;
String comparison rules:
1. If the characters in the same position are different, compare the sizes of different characters;
2. If the characters in the same position are the same, compare the length of the string;

public class Person{
	private String name;

	private int age;

	public Person() {
		super();
	}

	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;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}
// Customize a comparator
public class MyComparator implements Comparator{
 
	// Override the compare() method to define the comparison rules for the element:
	@Override
	public int compare(Object o1, Object o2) {
		
		Emp e1 = (Emp) o1;
		Emp e2 = (Emp) o2;
		
		// The return values are negative, 0 and positive, indicating that element object 1 is less than, equal to, and greater than element object 2;
		return e1.age- e2.age;
	}
}

public class TreeSetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Create a comparator object
		MyComparator comparator = new MyComparator();
		// Enter comparer when creating TreeSet
		TreeSet<Person> ts = new TreeSet(comparator);
		ts.add(new Person( "Chen Yi", 27));
		ts.add(new Person( "Feng ER", 32));
		ts.add(new Person( "Zhang San", 29));
		ts.add(new Person( "Li Si", 18));
		ts.add(new Person( "Wang Wu", 20));
		ts.add(new Person( "Zhao Liu", 28));
		ts.add(new Person( "Pseudo-ginseng", 33));
		
		System.out.println("Elements in collection:" + t);
	}
}
Published 10 original articles, won praise 3, visited 316
Private letter follow

Posted by neofox on Tue, 11 Feb 2020 05:21:09 -0800