我需要对包含数字的字符串集进行排序。 Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8]
。我需要将它分类到[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
。但是当我使用keyList设置的Collections.sort(keyList);
时,我得到的reult是[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]
。请帮忙。在java中对字符串数组进行排序
1
A
回答
0
可以尝试用:
final int[] searchList =
new int[] { 15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8 };
Arrays.sort(searchList);
结果是:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
名单必须int
2
编写自定义比较和分析它作为参数传递给Collections.sort(Collection,Comparator)
。一种解决方案是将你的字符串解析为整数。
Collections.sort(keyList, new Comparator<String>()
{
@Override
public int compare(String s1, String s2)
{
Integer val1 = Integer.parseInt(s1);
Integer val2 = Integer.parseInt(s2);
return val1.compareTo(val2);
}
});
0
改造String
s转换Integer
第一。
List<Integer> ints = new ArrayList<>();
for (String s : strings)
ints.add(Integer.parseInt(s));
Collections.sort(ints);
如果您不需要重复值,可以使用SortedSet
,它保持自动顺序:
SortedSet<Integer> ints = new TreeSet<>();
for (String s : strings)
ints.add(Integer.parseInt(s));
// all done!
0
你的字符串将在自然顺序进行排序为字符串,而不是作为数字。因此,在"10"
之后出现"11"
,"2"
出现在"11111111110"
之后。
该怎么办?
使用Integer.parseInt()
来解析集合中的每个字符串值为整数,然后将它们添加到集合中并调用Collections.sort()
。
0
你可以做的是凯表示,并转换您的字符串为整数,并比较其
,但它是昂贵的操作,我的建议是这样的:
keyList.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()){
return o1.compareTo(o2);
}
return o1.length() - o2.length();
}
});
,如果你的号码有相同的长度,然后使用String.compareTo
进行比较,否则按顺序对它们进行排序,因此1 2 3将自动在11之前22等。
相关问题
- 1. 如何在java中对字符串数组进行排序?
- 2. 在Java中对字符串数组进行排序
- 3. 对字符串数组进行排序
- 4. 对字符串数组进行排序
- 5. 按字符串中的数字对数组进行排序?
- 6. 对Java中包含数字的字符串进行排序
- 7. 在C++中对字符串数组进行排序
- 8. 如何在GUI中对字符串数组进行排序?
- 9. 在VB中对字符串数组进行排序的问题
- 10. 在BlackBerry中对字符串数组进行排序
- 11. 对字符串,组数据中的行进行排序
- 12. 在字符串之前对数组数值进行排序?
- 13. 在Java中对字符串数组按字母顺序排序
- 14. 根据字符串中的数字对字符串进行排序Java
- 15. 如何对C中数组中的字符串进行排序?
- 16. 对字符数组进行排序
- 17. 通过包含数字对字符串数组进行排序?
- 18. 对VTL中的字符串数组进行排序
- 19. 对C#中的字符串数组进行排序
- 20. 在对数组进行排序时忽略某些字符串
- 21. 基数使用Java中的队列对字符串数组进行排序
- 22. 在文本字符串中对数字进行排序
- 23. 在Ruby中对字符串和数字进行排序
- 24. Postgresql函数对字符串中的字符进行排序
- 25. 在Python中对字符串中的字符进行排序
- 26. 对字符串数组进行排序并忽略大小写
- 27. 对字符串数组进行不区分大小写排序
- 28. 尝试对字符串数组进行排序
- 29. 按字符串长度对三维数组进行排序PHP
- 30. 根据长度对字符串数组进行排序
字符串比较是按字母顺序排列的。尝试将其转换为整数列表以获得所需的结果。 – blackSmith 2014-09-19 12:28:30
请发布您使用的实际代码。 – wei2912 2014-09-19 12:28:43
Collections.sort接受一个Comparator作为参数。这使您可以自己定义比较功能。 (实际上,修改为int,然后比较值) – Ronald 2014-09-19 12:30:51