Skip to content
Related Articles

Related Articles

Improve Article

How to Sort LinkedHashSet of Custom Class Objects using TreeSet in Java?

  • Difficulty Level : Expert
  • Last Updated : 04 Jan, 2021
Geek Week

The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements present in java.util package. When the iteration order is needed to be maintained, this class is used.

TreeSet in Example

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

Approach 1:

In the example instead of using custom classes, the wrapper classes of java like Integer, Double, Float, etc to sort LinkedHashSet using TreeSet is used. For doing this convert LinkedHashSet element into TreeSet and can do this in three different ways:-



  1. By using the constructor of TreeSet.
  2. By using for loop and add() method.
  3. By using addAll() method.

Implementation:

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);
    }
}
Output
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]

 

Approach 2:

In this, the Comparator interface is used. Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes.

Implementation:

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :