Re-sort a LinkedHashSet

756 views Asked by At

Is there a method to sort the links in a LinkedHashSet? I know it preserves order in which the elements were added, but is there a way to re-sort those links as if it were a linked list, and have it still exhibit HashMap behaviors?

3

There are 3 answers

0
ish On

Unfortunately no, since sort() comes from List interface, which is not implemented by LinkedHashSet. It implements Set -> Collection interfaces.

But, there is a workaround, you can put data to ArrayList or LinkedList, sort it there and then put them to LinkedHashSet but now order will be sorted. Example:

ArraysList<> list = ..<put_your_data_here>..
list.sort(...); // with comparator
Set<> set = new LinkedHashSet(list);

As a result, you will have fully sorted LinkedHashSet.

0
sunil c.j On

You can achieve it in few ways.Sharing few which you can use

Way 1: Convert LinkedHashSet to TreeSet for natural-ordering

Steps:

  • Create new LinkedHashSet object
  • Store/add contents to LinkedHashSet
  • Create new TreeSet object,
  • Pass LinkedHashSet contents as argument to TreeSet’ inter-conversion constructor
package in.cj.resources.collection;

import java.util.LinkedHashSet;
import java.util.TreeSet;

public class SortingLinkedHashSetUsingTreeSet {

    public static void main(String[] args) {

        // creating LinkedHashSet object of type String
        LinkedHashSet<String> lhsCompanies = 
                new LinkedHashSet<String>();

        // adding elements to LinkedHashSet object
        lhsCompanies.add("Dutchview");
        lhsCompanies.add("Oracle");
        lhsCompanies.add("Microsoft");

        // Iterating using enhanced for-loop
        System.out.println("Insertion Order:"
                + " Iterating LinkedHashSet\n");
        for(String company : lhsCompanies) {
            System.out.println(company);
        }

        // convert LinkedHashSet to TreeSet
        TreeSet<String> tSet = new TreeSet<String>(lhsCompanies); 

        // Iterating using enhanced for-loop
        System.out.println("\n\nAscending sorting-order:"
                + " Iterating TreeSet\n");
        for(String company : tSet) {
            System.out.println(company);
        }
    }
}

Way 2: Convert LinkedHashSet to TreeSet for reverse-ordering

Steps:

  • Create new LinkedHashSet object Store/add contents to LinkedHashSet
  • Create new TreeSet object and provide reverse-order sorting-logic using Comparator Add LinkedHashSet contents to TreeSet using addAll() method
package in.cj.resources.collection;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class ReverseSortingLinkedHashSetUsingTreeSet {

    public static void main(String[] args) {

        // creating LinkedHashSet object of type String
        LinkedHashSet<String> lhsCompanies = 
                new LinkedHashSet<String>();

        // adding elements to LinkedHashSet object
        lhsCompanies.add("Dutchview");
        lhsCompanies.add("Amazon");
        lhsCompanies.add("Google");

        // Iterating using enhanced for-loop
        System.out.println("Insertion Order:"
                + " Iterating LinkedHashSet\n");
        for(String company : lhsCompanies) {
            System.out.println(company);
        }

        // create new TreeSet object and provide reverse-sorting logic
        TreeSet<String> tSet = new TreeSet<String>(
                new Comparator<String>() {

                    @Override
                    public int compare(String str1, String str2) {
                        return str2.compareTo(str1);
                    }
                }); 

        // add LinkedHashSet to TreeSet for reverse-sorting elements
        tSet.addAll(lhsCompanies);

        // Iterating using enhanced for-loop
        System.out.println("\n\nDescending sorting-order:"
                + " Iterating TreeSet\n");
        for(String company : tSet) {
            System.out.println(company);
        }
    }
}
0
M. Justin On

If for some reason you really need to update an ordering of an existing LinkedHashSet and can't create a new ordered one, you could create a ordered copy of the data, clear the original set, then add all the elements.

TreeSet<String> sortedCopy = new TreeSet<>(linkedHashSet);
linkedHashSet.clear();
linkedHashSet.addAll(sortedCopy);