Reputation: 5680
I have a set to sort (with Comparators) and I dont 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 a set and return the sorted set. I know, only linkedHashSet can preserve ordering.
Which one should I choose, I only want to sort the input properties users and return it, so is version 1 the best for that case? (For all cases, I want the references of input users be the same as for output users.)
EDIT: I think, I will choose version 4.
Upvotes: 10
Views: 12703
Reputation: 120848
I would add a 4-th method (if you are OK to change that method to return the sorted Set
)
users.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing...)))
I would return a SortedSet
to make it explicit for the caller that this is actually sorted.
If not you could do:
SortedSet<User> sorted = new TreeSet<>(Comparator.comparing...)
sorted.addAll(users);
Upvotes: 12
Reputation: 44150
Version one does effectively nothing. You are changing the reference of the parameter users
but not altering the set which is passed as an argument and not returning anything.
Version two works correctly.
Version three is attempting to store a sorted set in a set that does not maintain order. It's effectively no different than returning the set that you're given. From the JavaDoc for toSet
:
There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned
Upvotes: 5