¿Cómo ordenar LinkedHashSet de objetos de clase personalizados usando TreeSet en Java?

LinkedHashSet es una versión ordenada de HashSet que mantiene una lista doblemente enlazada en todos los elementos presentes en el paquete java.util . Cuando se necesita mantener el orden de iteración, se utiliza esta clase.

TreeSet en el ejemplo

Input : Student = {{"c",2},{"b",1},{"a",3}}
Output: 
Sort by name = {{"a",3},{"b",1},{"c",2}}
Sort by rollNo = {{"b",1},{"c",2},{"a",3}}

Enfoque 1:

En el ejemplo, en lugar de usar clases personalizadas, se usan las clases contenedoras de Java como Integer, Double, Float, etc. para ordenar LinkedHashSet usando TreeSet. Para hacer esto, convierta el elemento LinkedHashSet en TreeSet y puede hacerlo de tres maneras diferentes:

  1. Usando el constructor de TreeSet.
  2. Usando el método for loop y add().
  3. Usando el método addAll().

Implementación:

Java

// Java Program to sort LinkedHashSet of custom
// class objects using TreeSet
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.TreeSet;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // creating a LinkedHashSet
        LinkedHashSet<Double> lset0 = new LinkedHashSet<>();
  
        // adding elements to LinkedHashSet
        lset0.add(1.009);
        lset0.add(1.10);
        lset0.add(1.01);
        lset0.add(1.019);
  
        // creating a TreeSet
        // and adding LinkedHashSet element to TreeSet
        // using the constructor of the TreeSet
        TreeSet<Double> tset0 = new TreeSet<>(lset0);
  
        // Displaying the output
        System.out.println("Sorted Set(ascending): "
                           + tset0);
  
        // creating a LinkedHashSet
        LinkedHashSet<Integer> lset1
            = new LinkedHashSet<>();
  
        // adding elements to LinkedHashSet
        lset1.add(10);
        lset1.add(7);
        lset1.add(2);
        lset1.add(20);
  
        // creating TreeSet
        TreeSet<Integer> tset1 = new TreeSet<>();
  
        // adding LinkedHashSet element to TreeSet
        // using for loop and add() method
        for (Integer i : lset1)
            tset1.add(i);
  
        // Displaying the output
        System.out.println("Sorted Set(ascending): "
                           + tset1);
  
        // creating LinkedHashSet
        LinkedHashSet<Character> lset2
            = new LinkedHashSet<>();
  
        // adding elements to the LinkedHashSet
        lset2.add('s');
        lset2.add('h');
        lset2.add('i');
        lset2.add('n');
  
        // creating a TreeSet
        TreeSet<Character> tset2 = new TreeSet<>();
  
        // adding LinkedHashSet element to TreeSet
        // element using addAll() method
        tset2.addAll(lset2);
        System.out.println("Sorted Set(ascending): "
                           + tset2);
  
        // creating a LinkedHashSet
        LinkedHashSet<String> lset3 = new LinkedHashSet<>();
  
        // adding elements to the
        // LinkedHashSet
        lset3.add("Sandra");
        lset3.add("Shishya");
        lset3.add("Sarthak");
        lset3.add("Sarah");
        lset3.add("Sagar");
        lset3.add("Sashi");
        lset3.add("Sonika");
  
        // creating a TreeSet but this time it will
        // sort it in descending order
        // so for sorting in descending order
        // we will use Collections.reverseOrder() in
        // the constructor of TreeSet
        TreeSet<String> tset3
            = new TreeSet<>(Collections.reverseOrder());
  
        // adding elements of LinkedHashSet to treeSet
        // using addAll() method
        tset3.addAll(lset3);
  
        // Displaying output
        System.out.println("Sorted Set(descending): "
                           + tset3);
    }
}
Producción

Sorted Set(ascending): [1.009, 1.01, 1.019, 1.1]
Sorted Set(ascending): [2, 7, 10, 20]
Sorted Set(ascending): [h, i, n, s]
Sorted Set(descending): [Sonika, Shishya, Sashi, Sarthak, Sarah, Sandra, Sagar]

 

Enfoque 2:

En esto, se utiliza la interfaz Comparator. La interfaz del comparador se utiliza para ordenar los objetos de las clases definidas por el usuario. Un objeto comparador es capaz de comparar dos objetos de dos clases diferentes.

Implementación:

Java

Java Program to sort LinkedHashSet of custom
// class objects using TreeSet
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.TreeSet;
  
class friendsMarks {
  
    // class field
    String name;
    String nickName;
    int marks;
  
    // parameterised constructor
    public friendsMarks(String name, String nickName,
                        int marks)
    {
        this.name = name;
        this.nickName = nickName;
        this.marks = marks;
    }
  
    // getter for name
    public String getName() { return name; }
  
    // setter for name
    public void setName(String name) { this.name = name; }
  
    // getter for marks
    public int getMarks() { return marks; }
  
    // setter for marks
    public void setMarks(int marks) { this.marks = marks; }
  
    // getter for nickname
    public String getNickName() { return nickName; }
  
    // setter for nickname
    public void setNickName(String nickName)
    {
        this.nickName = nickName;
    }
  
    //@Override toString method
    public String toString()
    {
        return "friendsMarks{"
            + "name='" + name + '\'' + ", nickName='"
            + nickName + '\'' + ", marks=" + marks + '}';
    }
}
  
// for comparing names
class nameCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks friend1,
                       friendsMarks friend2)
    {
        return friend1.getName().compareTo(
            friend2.getName());
    }
}
  
// for comparing nick name
class nickNameCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks obj1, friendsMarks obj2)
    {
        return obj1.getNickName().compareTo(
            obj2.getNickName());
    }
}
  
// for comparing marks
class marksCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks f1, friendsMarks f2)
    {
        if (f1.getMarks() > f2.getMarks()) {
            return 1;
        }
        else {
            return -1;
        }
    }
}
public class Main {
  
    public static void main(String[] args)
    {
  
        // Creating LinkedHashSet
        LinkedHashSet<friendsMarks> linkedHashSet
            = new LinkedHashSet<>();
  
        // adding elements to LinkedHashSet
        linkedHashSet.add(
            new friendsMarks("Raushan", "Chamgader", 99));
        linkedHashSet.add(
            new friendsMarks("Yashdeep", "Dopa", 95));
        linkedHashSet.add(
            new friendsMarks("Rupesh", "Gian", 92));
        linkedHashSet.add(
            new friendsMarks("Shishya", "Gorilla", 47));
        linkedHashSet.add(
            new friendsMarks("Sarthak", "Nagin", 78));
        linkedHashSet.add(
            new friendsMarks("Sonika", "Chipkali", 67));
        linkedHashSet.add(
            new friendsMarks("Himanshu", "Lalten", 57));
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of marksCompare class
        // in the TreeSet constructor
        // so that we can sort according to the marks
        TreeSet<friendsMarks> treeSet0
            = new TreeSet<>(new marksCompare());
  
        // storing elements of LinkedHashSet
        // into TreeSet by using method addAll()
        treeSet0.addAll(linkedHashSet);
        System.out.println("Sorting on the basis of marks");
  
        // Displaying using loop
        for (friendsMarks tree : treeSet0)
            System.out.println(tree);
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of nameCompare class
        // in the TreeSet constructor
        // so that we can sort according to the name
        TreeSet<friendsMarks> treeSet1
            = new TreeSet<>(new nameCompare());
  
        // storing elements of LinkedHashSet
        // into TreeSet by using method addAll()
        treeSet1.addAll(linkedHashSet);
  
        // Displaying using loop
        System.out.println(
            "\n\nSorting on the basis of name");
        for (friendsMarks tree : treeSet1)
            System.out.println(tree);
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of nickNameCompare class
        // in the TreeSet constructor
        // so that we can sort according to the nickname
        TreeSet<friendsMarks> treeSet2
            = new TreeSet<>(new nickNameCompare());
  
        // storing elements of LinkedHashSet
        // into TreeSet by using method addAll()
        treeSet2.addAll(linkedHashSet);
  
        // Displaying using loop
        System.out.println(
            "\n\nSorting on the basis of nick-name");
        for (friendsMarks tree : treeSet2)
            System.out.println(tree);
    }
}
Producción

Sorting on the basis of marks
friendsMarks{name='Shishya', nickName='Gorilla', marks=47}
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}


Sorting on the basis of name
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}
friendsMarks{name='Shishya', nickName='Gorilla', marks=47}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}


Sorting on the basis of nick-name
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Shishya', nickName='Gorilla', marks=47}
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}

Publicación traducida automáticamente

Artículo escrito por le0 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *