'Sort contact list by name using Java stream.sort() [duplicate]

In my code I want to sort the contacts by their firstname, so I wrote the below method which is not working for me. Actually this code instead of giving me a sorted contact list it is giving me a normal unordered contactlist

public Set<Contact> sortContacts() {
    Set<Contact> sortedContacts = contactList.stream().sorted((c1, c2) -> c1.firstName.compareTo(c2.firstName)).collect(Collectors.toSet());
    return sortedContacts;
}


Solution 1:[1]

Each data structure has its own unique feature. A Set is an unordered list with no duplicate elements in it.

You need to use an Array or a List in order to keep the positions of your elements intact, such as in the case of sorting.

You can go through this blog to understand the difference between a Set and a List.

You can also modify the last chained method .collect(Collectors.toSet()) to .collect(Collectors.toList()), to acheive your desired result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MC Emperor