-2

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;
}
DevThiman
  • 920
  • 1
  • 9
  • 24

1 Answers1

0

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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31
  • 1
    thank u guys my first question had get answered this fast. unexpected guys – Kalimuthu K May 03 '22 at 08:14
  • 1
    Note that using a list is different insofar as it will not remove duplicate entries. If you want to remove duplicate entries, you need either to use `.distinct()` before collecting, or collect to an insertion-order-preserving set like `LinkedHashSet`. – Andy Turner May 03 '22 at 08:27