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 sorts a set and returns 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.
sort(listArr, new Comparator() { public int compare(Object arg0, Object arg1) { TheatreSeat r1 = (TheatreSeat) arg0; TheatreSeat r2 = (TheatreSeat) arg1; if (r2. getId() < r1. getId()) { return 1; } return 0; } });
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With