Java TreeSet使用(一) 自然排序 定制排序

向TreeSet中添加数据,必须是同一个类型的

可以按照添加进集合中的元素的指定顺序排序,默认按照从大到小的顺序遍历

当向TreeSet中添加自定义类的对象时,有两种排序方法:

1. 自然排序

要求自定义类实现java.lang.Comparable接口,并重写其抽象方法

向TreeSet中添加元素时,首先按照compareTo()进行比较,一旦返回0,虽然仅是两个对象的此属性值相同,但是程序会认为这两个对象是相同的,进而后一个对象就不能添加进来。

需要保证:compareTo() 与 hashCode() 与 equals相同

TreeSet使用实例-自然排序

package com.imekaku;

import org.junit.Test;

import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by lee on 2017/6/9.
 */
public class TestTreeSet {

    @Test
    public void test1() {
        Set set = new TreeSet();
        set.add("abc");
        // set.add(123); // 会报运行时异常
    }

    @Test
    public void test2() {
        Set<String> set = new TreeSet<>();
        set.add("abc");
        set.add(new String("123"));
        set.add(new String("xyz"));

        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        for (String s : set) {
            System.out.println(s);
        }
    }

    @Test
    public void test3() {
        Set<Integer> set = new TreeSet<>();
        set.add(11);
        set.add(55);
        set.add(33);

        for (Integer i : set) {
            System.out.println(i);
        }
    }

    /*
    *
    * 当往TreeSet中添加没有实现Comparable接口的类时,会报错
    * */
    @Test
    public void test4() {
        Set<Person> set = new TreeSet<>();
        set.add(new Person("CC", 23));
        set.add(new Person("BB", 44));
        set.add(new Person("VV", 11));
        set.add(new Person("KK", 11));

        for (Person p : set) {
            System.out.println(p);
        }
    }
}

class Person implements Comparable<Person> {
    public String name;
    public Integer age;

    public Person() {
    }

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

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

    @Override
    public int compareTo(Person o) {
        // return this.name.compareTo(o.name);
        int ageResult = this.age.compareTo(o.age);
        if (ageResult == 0) {
            return this.name.compareTo(o.name);
        }
        return ageResult;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(name, person.name) &&
                Objects.equals(age, person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

TreeSet定制排序

package com.imekaku;

import org.junit.Test;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by lee on 2017/6/9.
 */
public class TestTreeSet2 {

    @Test
    public void test1() {
        Comparator<Person> comparator = new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int ageResult = o1.age.compareTo(o2.age);
                if (ageResult == 0) {
                    return o1.name.compareTo(o2.name);
                }
                return ageResult;
            }
        };

        Set<Person> set = new TreeSet<>(comparator);
        set.add(new Person("DD", 11));
        set.add(new Person("CC", 11));
        set.add(new Person("FF", 12));

        for (Person p : set) {
            System.out.println(p);
        }
    }

    // 使用lambda表达式
    @Test
    public void test2() {
        Comparator<Person> comparator = ((o1, o2) -> {
            int ageResult = o1.age.compareTo(o2.age);
            if (ageResult == 0) {
                return o1.name.compareTo(o2.name);
            }
            return ageResult;
        });

        Set<Person> set = new TreeSet<>(comparator);
        set.add(new Person("DD", 11));
        set.add(new Person("CC", 11));
        set.add(new Person("FF", 12));

        for (Person p : set) {
            System.out.println(p);
        }
    }

    // 使用lambda表达式
    @Test
    public void test3() {
        Set<Person> set = new TreeSet<>(((o1, o2) -> {
            int ageResult = o1.age.compareTo(o2.age);
            if (ageResult == 0) {
                return o1.name.compareTo(o2.name);
            }
            return ageResult;
        }));

        set.add(new Person("DD", 11));
        set.add(new Person("CC", 11));
        set.add(new Person("FF", 12));

        for (Person p : set) {
            System.out.println(p);
        }
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部