使用集合排序对集合进行排序

时间:2021-04-18 23:41:03

标签: sorting

我正在尝试排序并需要作为一个集合保留。

所以,我正在尝试将我的集合转换为列表并使用 collection.sort 并再次隐蔽回集合但面临此错误: Collections 类型中的 sort(List) 方法不适用于参数 (ArrayList)

我尝试使用 treeset 进行排序,但它按词法排序,因此尝试使用 collections.sort

Set<Object> set = [11, 13, 24, 14, 25, 15, 26, 16, 27, 28, 18, 19, 1, 2, 3, 6];

ArrayList<Object> list = new ArrayList<Object>(set);
Collections.sort(list);

请帮助我哪里出错了。以上是我的示例代码

1 个答案:

答案 0 :(得分:0)

我认为使用 TreeSet 将是您的最佳选择,根据 constructor documentation,默认排序是元素的自然排序。使用您的特定伪代码示例(使用 Integers),这将非常完美:

var set1 = new TreeSet<>(Arrays.asList(
  11, 13, 24, 14, 25, 15, 26, 16, 
  27, 28, 18, 19, 1, 2, 3, 6
)); 
System.out.println(set1);
[1, 2, 3, 6, 11, 13, 14, 15, 16, 18, 19, 24, 25, 26, 27, 28]

但是,如果您使用 String,则使用词法排序,因为这是该类型的自然排序:

var set2 = new TreeSet<>(Arrays.asList(
  "11", "13", "24", "14", "25", "15", "26", "16",
  "27", "28", "18", "19", "1", "2", "3", "6" 
)); 
System.out.println(set2);
[1, 11, 13, 14, 15, 16, 18, 19, 2, 24, 25, 26, 27, 28, 3, 6]

您可以选择向 Comparator 提供 one of the constructors 以允许您根据自己的喜好自定义排序:

var set3 = new TreeSet<>((String a, String b) -> {
  return Integer.valueOf(a).compareTo(Integer.valueOf(b));
}); 
set3.addAll(Arrays.asList(
  "11", "13", "24", "14", "25", "15", "26", "16",
  "27", "28", "18", "19", "1", "2", "3", "6" 
)); 
System.out.println(set3);
[1, 2, 3, 6, 11, 13, 14, 15, 16, 18, 19, 24, 25, 26, 27, 28]