Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 stream.sorted with comparator in sets

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.

like image 951
nimo23 Avatar asked Jan 23 '18 12:01

nimo23


People also ask

How do you sort a set using Comparator?

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


Video Answer


1 Answers

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);
like image 98
Eugene Avatar answered Oct 12 '22 23:10

Eugene