Java 8 stream.sorted with comparator in sets

I have a set for sorting (using comparators), and I don’t know which version to choose:

version 1:

public static void sort(Set<User> users) { users = users.stream() .sorted(sort_gender.thenComparing(sort_age)) .collect(Collectors.toCollection(LinkedHashSet::new)); } 

version 2:

 public static Set<User> sort(Set<User> users) { return users.stream() .sorted(sort_gender.thenComparing(sort_age)) .collect(Collectors.toCollection(LinkedHashSet::new)); } 

version 3:

 public static void sort(Set<User> users) { users.stream() .sorted(sort_gender.thenComparing(sort_age)) .collect(Collectors.toSet()); } 

version 4

 public static List<User> sort(Set<User> users){ List<User> list = new ArrayList<>(users); list.sort(sort_gender.thenComparing(sort_age)); return list; } 

All versions sort the set and return the sorted set. I know only the associated HashSet can keep order.

Which one to choose , I only want to sort the properties of the input properties and return it, so that version 1 is best for this case? (For all cases, I want the input user links to be the same as the output users.)

EDIT: I think I will choose version 4.

+7
java java-8 comparator
source share
2 answers

I would add a 4th method (if you're ok, to change this method to return a sorted Set )

  users.stream() .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing...))) 

I would return a SortedSet to make it clear to the caller that this is really sorted.

If you can not do:

 SortedSet<User> sorted = new TreeSet<>(Comparator.comparing...) sorted.addAll(users); 
+7
source share

Version one really does nothing. You change the link for the users parameter, but do not change the set, which is passed as an argument and returns nothing.

Version 2 is working correctly.

The third version tries to save a sorted set in a set that does not support order. This is effectively no different from returning the kit you are given. From JavaDoc for toSet :

There are no guarantees regarding the type, variability, serializability or thread safety of the return set.

+5
source share

All Articles