java 8 stream.sorted with comparator in sets

nimo23 :

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.

Eugene :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439203&siteId=1