我试图对一组元素进行排序但是无法做到这一点.这是我正在尝试做的代码
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;
}
Run Code Online (Sandbox Code Playgroud)
但这种或其他方式不起作用,因为它始终给我相同的顺序,它们已被填充12,15,5
Sea*_*oyd 66
使用SortedSet(TreeSet是默认值):
SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);
Run Code Online (Sandbox Code Playgroud)
无需额外的排序代码.
哦,我看到你想要一个不同的排序顺序.为TreeSet提供比较器:
new TreeSet<String>(Comparator.comparing(Integer::valueOf));
Run Code Online (Sandbox Code Playgroud)
现在,您的TreeSet将按数字顺序对字符串进行排序(这意味着如果您提供非数字字符串,它将抛出异常)
参考:
TreeSetComparatormik*_*kej 29
如果你的字符串进行排序"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));
}
});
Run Code Online (Sandbox Code Playgroud)
另外,我认为你在Collection类型之间略有混淆.A HashSet和a HashMap是不同的东西.
您使用默认比较器对a进行排序Set<String>.在这种情况下,这意味着词典顺序.按字典顺序排在前面,"12"之前"15"来过"5".
要么使用Set<Integer>:
Set<Integer> set=new HashSet<Integer>();
set.add(12);
set.add(15);
set.add(5);
Run Code Online (Sandbox Code Playgroud)
或者使用不同的比较器:
Collections.sort(list, new Comparator<String>() {
public int compare(String a, String b) {
return Integer.parseInt(a) - Integer.parseInt(b);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138311 次 |
| 最近记录: |