Java Basics-Sorting of TreeSet and Java Custom Types

Demonstrate that TreeSet is sortable on String

1. The bottom layer of the TreeMap
collection is actually a TreeMap 2. The bottom layer of the TreeMap collection is a binary tree
3. The elements placed in the TreeSet collection are equivalent to being placed in the key part of the TreeMap collection 4. The elements in the TreeSet collection are
disordered and cannot be repeated. But it can be automatically sorted according to the size of the elements

called: sortable collection.
For example: write a program to retrieve data from the database, and display user information on the page in ascending or descending order of birthday. At
this time , you can use the TreeSet collection because the TreeSet collection is put in , Take it out is orderly.

//创建一个TreeSet集合
  TreeSet<String> ts=new TreeSet<>();
  //添加String
ts.add("zhangsan");
ts.add("lisi");
ts.add("wangwu");
ts.add("zhangsi");
ts.add("wangliu");
for(String s:ts){
    
    
      //按照字典顺序排序
      System.out.print(s+" ");
  }
  TreeSet<Integer> ts2=new TreeSet<>();
ts2.add(100);
ts2.add(200);
ts2.add(900);
ts2.add(800);  
ts2.add(600);
ts2.add(10);
for(Integer i:ts2){
    
    
      //按照升序排序
      System.out.print(i+" ");
}

Insert picture description here

TreeSet cannot sort custom types

Can TreeSet sort custom types?
In the following program, for the Person class, it is impossible to sort, because the comparison rules between Person objects are not specified. It is not stated who is big and who is small.

public class TreeSetTest02 {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person(50);
        Person p2=new Person(10);
        Person p3=new Person(20);
        Person p4=new Person(60);
        Person p5=new Person(40);
        Person p6=new Person(30);
        TreeSet<Person> persons=new TreeSet<>();
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        persons.add(p5);
        persons.add(p6);
        for(Person p:persons){
    
    
            System.out.println(p);
        }
    }
}
class Person{
    
    
    int age;
    public Person(int age){
    
    
        this.age=age;
    }
    @Override
    public String toString() {
    
    
        return "Person [age=" + age + "]";
    }
}
Exception in thread "main" java.lang.ClassCastException: testCollection.Person cannot be cast to java.lang.Comparable

The reason for this error is that the
Person class does not implement the java.lang, Comparable interface

//The elements placed in the TreeSet collection need to implement the java.lang.Comparable interface
//and implement the compareTo method, equals can be omitted

  public class TreeSetTest04 {
    
    
        public static void main(String[] args) {
    
    
            Customer p1=new Customer(50);
            Customer p2=new Customer(10);
            Customer p3=new Customer(20);
            Customer p4=new Customer(60);
            Customer p5=new Customer(40);
            Customer p6=new Customer(30);
            TreeSet<Customer> customers=new TreeSet<>();
            customers.add(p1);
            customers.add(p2);
            customers.add(p3);
            customers.add(p4);
            customers.add(p5);
            customers.add(p6);
            for(Customer p:customers){
    
    
                System.out.println(p);
            }
        }
    }
    //放在TreeSet集合中的元素需要实现java.lang.Comparable接口
//并且实现compareTo方法,equals可以不写
    class Customer implements Comparable<Customer>{
    
    
        int age;
        public Customer(int age){
    
    
            this.age=age;
        }
        @Override
        public String toString() {
    
    
            return "Customer [age=" + age + "]";
        }
        //需要在这个方法中编写比较的逻辑,或者说比较的规则,按照什么进行比较。
        //k.compareTo(t.key)
        //拿着参数k和集合中的每个k进行比较,返回值可能是>0,<0,=0
        //比较规则最终还是程序员实现的:例如按照年龄升序,或者按照年龄降序
        @Override
        public int compareTo(Customer c) {
    
        //c1.compareTo(c2)
// TODO Auto-generated method stub
            //this是c1
            //c是c2
            //c1和c2进行比较的时候,就是this和c比较
//    int age1=this.age;
//    int age2=c.age;
//    if(age1==age2){
    
    
//       return 0;
//    }else if(age1>age2){
    
    
//       return 1;
//    }else{
    
    
//       return -1;
//    }
            return this.age-c.age;    //>,<,=
        }

    }

//Need to write the logic of comparison in this method, or the rules of comparison, according to what to compare.
//k.compareTo(t.key)
//Compare the parameter k with each k in the set. The return value may be >0,<0,=0
//The comparison rule is finally implemented by the programmer: for example Sort by age ascending or descending by age

How to write comparison rules

First by age in ascending order, if the age is the same, then in ascending order by name

public class TreeSetTest05 {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Vip> vips=new TreeSet<>();
        vips.add(new Vip("zhangsi",20));
        vips.add(new Vip("zhangsan",20));
        vips.add(new Vip("king",18));
        vips.add(new Vip("soft",17));
        for(Vip vip:vips){
    
    
            System.out.println(vip);
        }
    }
}
class Vip implements Comparable<Vip>{
    
    
    String name;
    int age;
    public Vip(String name,int age){
    
    
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString() {
    
    
        return "Vip [name=" + name + ", age=" + age + "]";
    }
    //compareTo方法的返回值很重要:
    //返回0表示相同,value会覆盖
    //>0,会继续在右子树上找
    //<0,会继续在左子树上找

    @Override
    public int compareTo(Vip v) {
    
    
        if(this.age==v.age){
    
    
            //年龄相同时,按照名字排序
            //姓名是String类型,可以直接比,调用compareTo方法
            return this.name.compareTo(v.name);
        }else{
    
    
            //年龄不一样
            return this.age-v.age;
        }
    }

}

Self-balancing binary tree structure

1. Self-balancing binary tree, store according to the principle of small left and big right
2. When traversing a binary tree, there are three ways.
Pre-
order traversal: left and right roots. Middle-order traversal: left root and right.
Post-order traversal: left and right roots
. The position of the root
3. The TreeSet collection and the TreeMap collection use an in-order traversal method, that is, left root right. They are self-balancing binary trees
100 200 50 60 80 120 140 130 135 180 666

Implement the comparator interface

The second way to sort the elements in the TreeSet collection is to use the comparator

public class TreeSetTest06 {
    
    
    public static void main(String[] args) {
    
    
        //创建TreeSet集合的时候,需要使用比较器
        //TreeSet<Wugui> wuGuis=new TreeSet<>();   //这样不行,没有通过构造方法传递一个比较器进去
        TreeSet<Wugui> wuGuis=new TreeSet<>(new WuguiComparator());
        wuGuis.add(new Wugui(1000));
        wuGuis.add(new Wugui(800));
        wuGuis.add(new Wugui(900));
        wuGuis.add(new Wugui(300));
        wuGuis.add(new Wugui(60));
        for(Wugui wugui:wuGuis){
    
    
            System.out.println(wugui);
        }

    }
}
class Wugui{
    
    
    int age;

    public Wugui(int age) {
    
    
        super();
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Wugui [age=" + age + "]";
    }
}
//单独再这里编写一个比较器
//比较器实现java.util.Comparator接口(Comparable是java.lang包下的)
class WuguiComparator implements Comparator<Wugui>{
    
    
    public int compare(Wugui o1,Wugui o2){
    
    
        //指定比较规则
        //按照年龄排序
        return o1.age-o2.age;
    }
}

Insert picture description here
We can use the way of anonymous inner classes. We can use the way of
anonymous inner classes (this class has no name, directly new interface)

TreeSet<Wugui> wuGuis=new TreeSet<>(new Comparator<Wugui>(){
    
    
public int compare(Wugui o1,Wugui o2){
    
    
        //指定比较规则
        //按照年龄排序
        return o1.age-o2.age;
        }

});

The final conclusion is that there are two ways to sort the elements in the key part of the TreeSet or TreeMap collection. The
first is: the elements in the collection implement the java.lang.Comparable interface.
The second: in the construction of the TreeSet or TreeMap. When collecting, pass it a comparator object.

How to choose Comparable and Comparator?
When the comparison rule does not change, or when there is only one comparison rule, it is recommended to implement the Comparable interface.
If there are multiple comparison rules and frequent switching between multiple comparison rules is required, it is recommended to use the
comparator interface. The design complies with OCP principles.

Collections tools

java.util.Collections collection tool class to facilitate collection operations

public class CollectionsTest {
    
    
    static class Wugui2 implements Comparable<Wugui2>{
    
    
        int age;

        public Wugui2(int age) {
    
    
            super();
            this.age = age;
        }

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

        @Override
        public int compareTo(Wugui2 o) {
    
    
            // TODO Auto-generated method stub
            return this.age-o.age;
        }
    }
    public static void main(String[] args) {
    
    
        //ArrayList集合不是线程安全的
        List<String> list=new ArrayList<String>();
        //变成线程安全的
        Collections.synchronizedList(list);
        //排序
        list.add("abc");
        list.add("abe");
        list.add("abd");
        list.add("abf");
        list.add("abn");
        list.add("abm");
        Collections.sort(list);
        for(String s:list){
    
    
            System.out.println(s);
        }
        List<Wugui2> wuguis=new ArrayList<>();
        wuguis.add(new Wugui2(1000));
        wuguis.add(new Wugui2(8000));
        wuguis.add(new Wugui2(4000));
        wuguis.add(new Wugui2(6000));
        //注意:对list集合中元素排序,需要保证list集合中元素实现了Comparable接口
        Collections.sort(wuguis);
        for(Wugui2 wugui:wuguis){
    
    
            System.out.println(wugui);
        }
        //对set集合怎么排序呢
        Set<String> set=new HashSet<>();
        set.add("king");
        set.add("kingsoft");
        set.add("king2");
        set.add("king1");
        //将set集合转换成list集合
        List<String> myList=new ArrayList<>(set);
        Collections.sort(myList);
        for(String s:myList){
    
    
            System.out.println(s);
        }
        //这种方式也可以排序
        //Collections.sort(list集合,比较器对象)
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/112195737