📜  在Java中通过用户定义对象创建带有比较器的 TreeSet

📅  最后修改于: 2022-05-13 01:54:23.063000             🧑  作者: Mango

在Java中通过用户定义对象创建带有比较器的 TreeSet

TreeSet 是 Set 接口的实现类。它遵循自然的排序顺序,或者您可以使用比较器对其进行自定义,并且它也不允许重复。

句法:

TreeSet gfg= new TreeSet<>();

下面是 TreeSet 的正常实现:

Java
// Java program for TreeSet
import java.io.*;
import java.util.TreeSet;
 
class GFG {
    public static void main(String[] args)
    {
         
        TreeSet gfg = new TreeSet();
 
        // adding elements in Treeset using add() method
        gfg.add("first");
        gfg.add("second");
        gfg.add("third");
        gfg.add("fourth");
        gfg.add("fifth");
 
        // iterating over the TreeSet using
        // foreach loop and printing it
        for (String value : gfg) {
            System.out.println(value);
        }
    }
}


Java
// Java program for treeset of user
// defined objects and using comparator
 
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
 
class GFG {
    public static void main(String[] args)
    {
        // TreeSet of user defined objects
        // and using comparator also
        // we will create TreeSet of employees
        System.out.println(
            "Sorting on the basis of name in Ascending order");
 
        // passed first comparator object for
        // sorting in ascending order of name
        TreeSet gfg
            = new TreeSet<>(new FirstComparator());
 
        gfg.add(new Employee(1, "ram", 24));
        gfg.add(new Employee(2, "krishna", 23));
        gfg.add(new Employee(3, "sita", 26));
        gfg.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg) {
            System.out.println(employee);
        }
 
        System.out.println(
            "Sorting on the basis of name in Descending order");
 
        // Passed second comparator object for
        // Sorting in descending order of name
        TreeSet gfg2
            = new TreeSet<>(new SecondComparator());
        gfg2.add(new Employee(1, "ram", 24));
        gfg2.add(new Employee(2, "krishna", 23));
        gfg2.add(new Employee(3, "sita", 26));
        gfg2.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg2) {
            System.out.println(employee);
        }
 
        // ThirdComparator
        System.out.println(
            "Sorting on the basis of age in ascending order");
 
        TreeSet gfg3
            = new TreeSet<>(new ThirdComparator());
 
        gfg3.add(new Employee(1, "ram", 24));
        gfg3.add(new Employee(2, "krishna", 23));
        gfg3.add(new Employee(3, "sita", 26));
        gfg3.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg3) {
            System.out.println(employee);
        }
    }
}
 
// for sorting in ascending order
class FirstComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        return (e1.name).compareTo(e2.name);
    }
}
 
// for sorting in descending order
// passed in reverse order e2 first than e1
class SecondComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        return -(e1.name).compareTo(e2.name);
    }
}
 
// Sorted on the basis of age
class ThirdComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        if (e1.age > e2.age) {
            return -1;
        }
        else if (e1.age < e2.age) {
            return 1;
        }
        else {
            return (e1.age).compareTo(e2.age);
        }
    }
}
 
// Employee class
class Employee {
 
    // Employee has three attributes
    // id , name, age
 
    public int id;
    public String name;
    public Integer age;
 
    // default constructor
    Employee() {}
 
    // parameterized constructor
    Employee(int id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    @Override public String toString()
    {
        return "" + this.id + " " + this.name + " "
            + this.age;
    }
}


Java
// Java program for treeset of user
// defined objects and using comparator
 
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
 
class GFG {
    public static void main(String[] args)
    {
        // TreeSet of user defined objects
        // we will create TreeSet of employees
        System.out.println(
            "Sorting on the basis of name ascending order");
 
        // passing comparator using lambda expressions
        TreeSet gfg
            = new TreeSet<>((Employee e1, Employee e2)
                                ->
                            - (e1.name).compareTo(e2.name));
 
        gfg.add(new Employee(1, "ram", 24));
        gfg.add(new Employee(2, "krishna", 23));
        gfg.add(new Employee(3, "sita", 26));
        gfg.add(new Employee(4, "lakshman", 25));
 
        for (Employee employee : gfg) {
            System.out.println(employee);
        }
 
        // SecondComparator
        System.out.println(
            "Sorting on the basis of name ascending order");
 
        TreeSet gfg2 = new TreeSet<>(
            (Employee e1,
             Employee e2) -> e1.name.compareTo(e2.name));
 
        // adding employee object to treeSet
        gfg2.add(new Employee(1, "ram", 24));
        gfg2.add(new Employee(2, "krishna", 23));
        gfg2.add(new Employee(3, "sita", 26));
        gfg2.add(new Employee(4, "lakshman", 25));
 
        // printing every employee object
        for (Employee employee : gfg2) {
            System.out.println(employee);
        }
    }
}
 
class Employee {
    // Employee has three attributes
    // id , name, age
 
    public int id;
    public String name;
    public Integer age;
 
    // default constructor
    Employee() {}
 
    // parameterized constructor
    Employee(int id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    @Override public String toString()
    {
        return "" + this.id + " " + this.name + " "
            + this.age;
    }
}


输出
fifth
first
fourth
second
third

使用 Comparator 为用户定义的对象创建 TreeSet

1. 使用接口制作比较器对象:

首先,我们将创建一个 Employee 类,该类具有属性 age、id、name 以及一个默认构造函数和一个参数化构造函数。现在我们需要创建实现比较器接口的 Comparator 类,并需要覆盖 compare() 方法。比较器方法的返回类型是整数(1, -1, 0)。

例如对象为(对象 o1,对象 o2)  

对于升序(整数)

if(o1o2) return +1;
else return 0;

对于降序(整数)

if(o1o2) return -1;
else return 0;

对于按升序排列的字符串

return s1.compareTo(s2); //here s1 , s2 are strings

对于降序的字符串

return -s1.compareTo(s2);//here s1 , s2 are strings

现在我们将创建一个由员工和员工组成的 TreeSet 并且在构造函数中,我们需要传递比较器对象

句法 :

TreeSet gfg=new TreeSet<>(comparatorObject);
gfg.add(new Employee(1,"raja",23);

下面是上述问题陈述的实现:

Java

// Java program for treeset of user
// defined objects and using comparator
 
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
 
class GFG {
    public static void main(String[] args)
    {
        // TreeSet of user defined objects
        // and using comparator also
        // we will create TreeSet of employees
        System.out.println(
            "Sorting on the basis of name in Ascending order");
 
        // passed first comparator object for
        // sorting in ascending order of name
        TreeSet gfg
            = new TreeSet<>(new FirstComparator());
 
        gfg.add(new Employee(1, "ram", 24));
        gfg.add(new Employee(2, "krishna", 23));
        gfg.add(new Employee(3, "sita", 26));
        gfg.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg) {
            System.out.println(employee);
        }
 
        System.out.println(
            "Sorting on the basis of name in Descending order");
 
        // Passed second comparator object for
        // Sorting in descending order of name
        TreeSet gfg2
            = new TreeSet<>(new SecondComparator());
        gfg2.add(new Employee(1, "ram", 24));
        gfg2.add(new Employee(2, "krishna", 23));
        gfg2.add(new Employee(3, "sita", 26));
        gfg2.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg2) {
            System.out.println(employee);
        }
 
        // ThirdComparator
        System.out.println(
            "Sorting on the basis of age in ascending order");
 
        TreeSet gfg3
            = new TreeSet<>(new ThirdComparator());
 
        gfg3.add(new Employee(1, "ram", 24));
        gfg3.add(new Employee(2, "krishna", 23));
        gfg3.add(new Employee(3, "sita", 26));
        gfg3.add(new Employee(4, "lakshman", 25));
 
        // printing each employee object
        for (Employee employee : gfg3) {
            System.out.println(employee);
        }
    }
}
 
// for sorting in ascending order
class FirstComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        return (e1.name).compareTo(e2.name);
    }
}
 
// for sorting in descending order
// passed in reverse order e2 first than e1
class SecondComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        return -(e1.name).compareTo(e2.name);
    }
}
 
// Sorted on the basis of age
class ThirdComparator implements Comparator {
    @Override public int compare(Employee e1, Employee e2)
    {
        if (e1.age > e2.age) {
            return -1;
        }
        else if (e1.age < e2.age) {
            return 1;
        }
        else {
            return (e1.age).compareTo(e2.age);
        }
    }
}
 
// Employee class
class Employee {
 
    // Employee has three attributes
    // id , name, age
 
    public int id;
    public String name;
    public Integer age;
 
    // default constructor
    Employee() {}
 
    // parameterized constructor
    Employee(int id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    @Override public String toString()
    {
        return "" + this.id + " " + this.name + " "
            + this.age;
    }
}
输出
Sorting on the basis of name in Ascending order
2 krishna 23
4 lakshman 25
1 ram 24
3 sita 26
Sorting on the basis of name in Descending order
3 sita 26
1 ram 24
4 lakshman 25
2 krishna 23
Sorting on the basis of age in ascending order
3 sita 26
4 lakshman 25
1 ram 24
2 krishna 23

2.使用Java 8 lambda表达式:

这里我们不会创建单独的类来实现比较器接口,因此不需要覆盖比较方法。现在我们只需要在 TreeSet 的构造函数中直接使用 lambda 表达式,其余的都是一样的,唯一不同的是这里我们使用 lambda 作为比较器对象

句法 :

TreeSet gfg2=new TreeSet<>(
(Employee e1 , Employee e2)->e1.name.compareTo(e2.name));

下面是问题陈述的实现:

Java

// Java program for treeset of user
// defined objects and using comparator
 
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
 
class GFG {
    public static void main(String[] args)
    {
        // TreeSet of user defined objects
        // we will create TreeSet of employees
        System.out.println(
            "Sorting on the basis of name ascending order");
 
        // passing comparator using lambda expressions
        TreeSet gfg
            = new TreeSet<>((Employee e1, Employee e2)
                                ->
                            - (e1.name).compareTo(e2.name));
 
        gfg.add(new Employee(1, "ram", 24));
        gfg.add(new Employee(2, "krishna", 23));
        gfg.add(new Employee(3, "sita", 26));
        gfg.add(new Employee(4, "lakshman", 25));
 
        for (Employee employee : gfg) {
            System.out.println(employee);
        }
 
        // SecondComparator
        System.out.println(
            "Sorting on the basis of name ascending order");
 
        TreeSet gfg2 = new TreeSet<>(
            (Employee e1,
             Employee e2) -> e1.name.compareTo(e2.name));
 
        // adding employee object to treeSet
        gfg2.add(new Employee(1, "ram", 24));
        gfg2.add(new Employee(2, "krishna", 23));
        gfg2.add(new Employee(3, "sita", 26));
        gfg2.add(new Employee(4, "lakshman", 25));
 
        // printing every employee object
        for (Employee employee : gfg2) {
            System.out.println(employee);
        }
    }
}
 
class Employee {
    // Employee has three attributes
    // id , name, age
 
    public int id;
    public String name;
    public Integer age;
 
    // default constructor
    Employee() {}
 
    // parameterized constructor
    Employee(int id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
 
    @Override public String toString()
    {
        return "" + this.id + " " + this.name + " "
            + this.age;
    }
}
输出
Sorting on the basis of name ascending order
3 sita 26
1 ram 24
4 lakshman 25
2 krishna 23
Sorting on the basis of name ascending order
2 krishna 23
4 lakshman 25
1 ram 24
3 sita 26