排序集的值 [英] Sorting Values of Set
问题描述
我正在尝试对一组元素进行排序但是无法做到这一点。
这里是我正在尝试做的代码
I am trying to sort elements of a set but unable to do so far. here is my code which i am trying to do
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
but this or other way is not working since its all time giving me the same order in which they have been filled 12,15,5
推荐答案
如果你对字符串进行排序12
,15
和5
然后5
排在最后,因为5
> 1
。即,字符串的自然顺序不会按预期的方式工作。
If you sort the strings "12"
, "15"
and "5"
then "5"
comes last because "5"
> "1"
. i.e. the natural ordering of Strings doesn't work the way you expect.
如果要在列表中存储字符串,但是在数字上对它们进行排序,那么您将需要使用处理这个的比较器。例如
If you want to store strings in your list but sort them numerically then you will need to use a comparator that handles this. e.g.
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 $之间略有混淆c $ c>类型。
HashSet
和 HashMap
是不同的东西。
Also, I think you are getting slightly mixed up between Collection
types. A HashSet
and a HashMap
are different things.
这篇关于排序集的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!