如何排序包含数字的字符串集合? [英] How to sort a String collection that contains numbers?
问题描述
我有一个包含如下数据的字符串向量:
I have a String Vector that contains data like this :
5:34,5:38,17:21,22: 11,...
5:34, 5:38, 17:21, 22:11, ...
如果我尝试使用 Collections.sort(...); 它将显示如下:
If i try to merge this using Collections.sort( ... ); it will appear like this :
17:21,22:11,5:34,5:38
17:21, 22:11, 5:34, 5:38
其实我希望它像这样出现:
Actually i want it to appear like this :
34,5:38,17:21,22:11
5:34, 5:38, 17:21, 22:11
所以我想根据冒号前的数字排序元素:,那么如果一些元素在:之前有相同的数字,则根据:后的数字对它们进行排序。
So i want to sort the elements according to the number before the colon ":" then if some elements have the same number before ":" then sort them according to the number after the ":".
推荐答案
您可以创建一个自定义 Comparator
拆分 String
并将其解析为两个int 或创建一个定制类来表示每个 String
,并将其存储在 Collection
中。我赞成后一种方法,因为你只产生分割/解析字符串一次的开销;例如
You could either create a custom Comparator
to split the String
and parse it into two ints, or create a bespoke class to represent each String
and store that in the Collection
instead. I favour the latter approach as you only incur the overhead of splitting / parsing the String once; e.g.
public class Data implements Comparable<Data> {
private final int prefix;
private final int suffix;
public Data(String str) {
String[] arr = str.split(":");
if (arr.length != 2) {
throw new IllegalArgumentException();
}
this.prefix = Integer.parseInt(arr[0]);
this.suffix = Integer.parseInt(arr[1]);
}
public int compareTo(Data data) {
// Should really avoid subtraction in case of overflow but done to keep code brief.
int ret = this.prefix - data.prefix;
if (ret == 0) {
ret = this.suffix - data.suffix;
}
return ret;
}
// TODO: Implement equals and hashCode (equals to be consistent with compareTo).
public String toString() { return String.format("%d:%d", prefix, suffix); }
}
然后它只是一个存储一些数据
对象;例如集合
中的
Then it's simply a case of storing some Data
objects in your Collection
; e.g.
List<Data> l = new ArrayList<Data>();
l.add(new Data("13:56"));
l.add(new Data("100:16"));
l.add(new Data("9:1"));
Collections.sort(l);
还有一件事 - 你提到你使用 Vector
。您应该尽量避免使用向量
/ Hashtable
,因为这些已被 code> /
Map
,作为JDK 1.2中的集合框架的一部分。
One more thing - You mention you're using a Vector
. You should try to avoid using Vector
/ Hashtable
as these have been superseded by List
/ Map
, which were introduced as part of the Collections Framework in JDK 1.2.
这篇关于如何排序包含数字的字符串集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!