我有一组要排序(使用比较器),但我不知道要选择哪个版本:
版本1:
public static void sort(Set<User> users) {
users = users.stream()
.sorted(sort_gender.thenComparing(sort_age))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
版本2:
public static Set<User> sort(Set<User> users) {
return users.stream()
.sorted(sort_gender.thenComparing(sort_age))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
版本3:
public static void sort(Set<User> users) {
users.stream()
.sorted(sort_gender.thenComparing(sort_age))
.collect(Collectors.toSet());
}
版本4
public static List<User> sort(Set<User> users){
List<User> list = new ArrayList<>(users);
list.sort(sort_gender.thenComparing(sort_age));
return list;
}
所有版本都会对集合进行排序,并返回排序后的集合。我知道,只有linkedHashSet可以保留排序。
我应该选择哪个,我只想对输入属性用户进行排序并返回它,那么对于这种情况,版本1是最好的吗? (对于所有情况,我希望输入用户的引用与输出用户的引用相同。)
编辑:我认为,我将选择版本4。
最佳答案
我将添加第4种方法(如果可以更改该方法以返回排序后的Set
)
users.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing...)))
我将返回一个
SortedSet
,以明确告知调用者它实际上已排序。如果没有,你可以做:
SortedSet<User> sorted = new TreeSet<>(Comparator.comparing...)
sorted.addAll(users);