SoFunction
Updated on 2025-04-06

Java 8 How to sort LinkedHashSet elements

introduction

LinkedHashSet is a class in the Java collection framework. It inherits from HashSet and implements the Set interface. Unlike HashSet, LinkedHashSet maintains the insertion order of elements through a linked list, so when it traverses LinkedHashSet, elements appear in the order in which they are inserted.

However, LinkedHashSet does not support sorting of elements, it only maintains the insertion order. Therefore, in some cases, we may want to sort the elements in the LinkedHashSet to meet specific business needs.

How to sort LinkedHashSet elements in Java 8?

In Java 8, the basic idea of ​​sorting is to convert LinkedHashSet to List, and then use the sorting ability of List to sort. Next, we will discuss several common sorting methods, including using the Stream API, Comparator, and () etc.

Sort LinkedHashSet using the Stream API

Java 8 introduces the Stream API, which makes sorting collections more convenient. By streaming, we can convert LinkedHashSet to List and sort it. Here are the implementation steps:

Step 1: Convert LinkedHashSet to List

StreamThe API provides()Method, you canStreamThe elements in the collection areListmiddle.

Step 2: Sort List

StreamThe API providessorted()Method, this method returns a sorted stream. If you need to customize the sorting rules, you can pass in oneComparator

Step 3: Turn the sorted List back to LinkedHashSet

The sorted elements can be passedLinkedHashSetThe constructor ofLinkedHashSet, to maintain the insertion order.

Sample code:

import .*;
import ;

public class LinkedHashSetSortExample {
    public static void main(String[] args) {
        // Create LinkedHashSet        LinkedHashSet<Integer> set = new LinkedHashSet<>((5, 3, 7, 1, 4, 2));

        // Sort LinkedHashSet using Stream API        LinkedHashSet<Integer> sortedSet = ()
            .sorted(())  // Sort in ascending order            .collect((LinkedHashSet::new));

        // Output the sorted result        ("Sorted LinkedHashSet: " + sortedSet);
    }
}

explain:

  1. ():WillLinkedHashSetConvert to stream.
  2. sorted(()): Sort in ascending order.
  3. collect((LinkedHashSet::new)): Collect the sorted stream back to a new oneLinkedHashSetmiddle.

Output result:

Sorted LinkedHashSet: [1, 2, 3, 4, 5, 7]

Use Comparator to customize the sorting of LinkedHashSet

If we want to sort by custom rules, we can useComparatorProvides more flexibility. For example, we can sort in descending order, by a certain attribute of the object, etc.

Sample code:

import .*;
import ;

public class LinkedHashSetSortCustomExample {
    public static void main(String[] args) {
        // Create LinkedHashSet        LinkedHashSet<String> set = new LinkedHashSet<>(("apple", "banana", "cherry", "date"));

        // Sort LinkedHashSet in descending order using Stream API and custom Comparator        LinkedHashSet<String> sortedSet = ()
            .sorted(())  // Sort in descending order            .collect((LinkedHashSet::new));

        // Output the sorted result        ("Sorted LinkedHashSet in reverse order: " + sortedSet);
    }
}

explain:

  • (): Custom sorting method, sort strings in descending order.

Output result:

Sorted LinkedHashSet in reverse order: [date, cherry, banana, apple]

Use () to sort LinkedHashSet

() is a traditional sorting method provided by Java, which requires that the sorted collection must be of List type. So, first you need to convert the LinkedHashSet to a List and then sort the List with ().

Sample code:

import .*;

public class LinkedHashSetSortUsingCollections {
    public static void main(String[] args) {
        // Create LinkedHashSet        LinkedHashSet<Integer> set = new LinkedHashSet<>((5, 3, 7, 1, 4, 2));

        // Convert LinkedHashSet to List        List<Integer> list = new ArrayList<>(set);

        // Use () to sort List        (list);  // Sort in ascending order
        // Output the sorted result        ("Sorted List: " + list);
    }
}

explain:

  • WillLinkedHashSetConvert toArrayList,because()Only rightListSort.
  • use(list)Sort the list.

Output result:

Sorted List: [1, 2, 3, 4, 5, 7]

Use TreeSet instead of LinkedHashSet to implement sorting

If you do not need to preserve the insertion order of LinkedHashSet, but instead want the sorted collection elements to be arranged in a certain order, you can use TreeSet. TreeSet is a collection that implements the SortedSet interface, which sorts according to the natural order of elements or the given Comparator.

Sample code:

import .*;

public class TreeSetSortExample {
    public static void main(String[] args) {
        // Create LinkedHashSet        LinkedHashSet<Integer> set = new LinkedHashSet<>((5, 3, 7, 1, 4, 2));

        // Sort elements with TreeSet        Set<Integer> sortedSet = new TreeSet<>(set);

        // Output the sorted result        ("Sorted Set using TreeSet: " + sortedSet);
    }
}

explain:

  • TreeSetThe elements in the collection will be automatically sorted, and by default, they are sorted in natural order (ascending order).

Output result:

Sorted Set using TreeSet: [1, 2, 3, 4, 5, 7]

Summarize

In Java 8, you can use the following methods to matchLinkedHashSetElements are sorted:

  1. useStream API: Through flowLinkedHashSetConvert toList, and then sort. Can be usedComparatorCustomize the sorting rules, and finally collect the sorted elements into newLinkedHashSetmiddle.
  2. useComparator: Through customComparatorrightLinkedHashSetThe elements in  sort.
  3. use(): FirstLinkedHashSetConvert toList, and then use the traditional sorting method()Sort.
  4. useTreeSet: If you do not need to preserve the insertion order, you can useTreeSetTo automatically sort.

The above is the detailed content of Java 8's operation method to sort LinkedHashSet elements. For more information on sorting Java 8's LinkedHashSet elements, please follow my other related articles!