【问题标题】:Sorting Values of Set对 Set 的值进行排序
【发布时间】:2010-11-12 14:54:08
【问题描述】:

我正在尝试对集合中的元素进行排序,但目前还无法做到。 这是我正在尝试做的代码

public static void main(String [] args){
    Set<String> set=new HashSet<String>();
    set.add("12");
    set.add("15");
    set.add("5");
    List<String> list=asSortedList(set);
}

public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
  List<T> list = new ArrayList<T>(c);
  Collections.sort(list);
  return list;
}

但是这种或其他方式不起作用,因为它一直给我相同的顺序,它们已被填充 12,15,5

【问题讨论】:

  • Map 不是Set。大不同!
  • 如果你想要一个排序集,你有什么理由不使用排序集?

标签: java collections


【解决方案1】:

使用 SortedSet(TreeSet 是默认的):

SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);

不需要额外的排序代码。

哦,我知道你想要一个不同的排序顺序。为 TreeSet 提供一个比较器:

new TreeSet<String>(Comparator.comparing(Integer::valueOf));

现在您的 TreeSet 将按数字顺序对字符串进行排序(这意味着如果您提供非数字字符串,它将引发异常)

参考:

【讨论】:

  • 你也可以将Comparator传递给TreeSet的构造函数
【解决方案2】:

如果您对字符串"12""15""5" 进行排序,那么"5" 排在最后,因为"5" > "1"。即,字符串的自然排序不会按您期望的方式工作。

如果您想将字符串存储在列表中但按数字排序,则需要使用比较器来处理此问题。例如

Collections.sort(list, new Comparator<String>() {
    public int compare(String o1, String o2) {
        Integer i1 = Integer.parseInt(o1);
        Integer i2 = Integer.parseInt(o2);
        return (i1 > i2 ? -1 : (i1 == i2 ? 0 : 1));
    }
});

另外,我认为您在 Collection 类型之间有点混淆了。 HashSetHashMap 是不同的东西。

【讨论】:

  • +1 ... 虽然:在比较期间从另一个 int 中减去一个 int 可能会导致下溢;显式比较会更安全。
  • o1 == o2 可能会导致非实习字符串的意外结果。使用o1.equals(o2)(你也可以使用o1.intern()==o2.intern(),但这太糟糕了)
  • 谢谢@seanizer - 我并不是真的要比较字符串。我在编辑中失去了对parseInt 的呼叫。我又修改了一遍。
  • 您的退货声明不能简化为return i1.compareTo(i2);吗?
【解决方案3】:

您正在使用默认比较器对Set&lt;String&gt; 进行排序。在这种情况下,这意味着lexicographic order。按字典顺序,"12""15" 之前,在 "5" 之前。

要么使用Set&lt;Integer&gt;

Set<Integer> set=new HashSet<Integer>();
set.add(12);
set.add(15);
set.add(5);

或者使用不同的比较器:

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.parseInt(a) - Integer.parseInt(b);
    }
});

【讨论】:

    【解决方案4】:

    使用Integer 包装类而不是String,因为它通过实现Comparable&lt;Integer&gt; 为您完成了艰苦的工作。然后java.util.Collections.sort(list); 就可以了。

    【讨论】:

      【解决方案5】:

      Strings are sorted lexicographically。您看到的行为是正确的。

      随意定义your own comparator to sort the strings

      如果您将集合更改为 Integer 而不是使用 String,它也会按照您期望的方式工作(5 作为第一个元素)。

      【讨论】:

        【解决方案6】:

        您需要将 Comparator 实例传递给 sort 方法,否则元素将按其自然顺序排序。

        更多信息请查看Collections.sort(List, Comparator)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-06
          • 2011-01-08
          • 1970-01-01
          • 1970-01-01
          • 2016-11-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多