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.
java java-8 comparator
nimo23
source share