先说,我看的很类似的问题,但我认为这是不重复的。
First to say that I see very similar questions but i think this is not duplicate.
我需要字符串数组列表,列表中的成员都是格式进行排序 ID ::名称
键,其中 ID
一些数字和名称
一些字符串。
I need to sort string array list where members of list are in format ID::NAME
and where ID
is some number and name
some string.
第一个想法是简单的我用
First idea was simple I use
ArrayList<String> my_list = new ArrayList<String>();
my_list.add("0" + "::" + "ABC");
my_list.add("2" + "::" + "DBC");
my_list.add("1" + "::" + "DDC");
my_list.add("10" + "::" + "DBD");
my_list.add("22" + "::" + "DDD");
(etc...)
Collections.sort(my_list);
问题是,在排序的这种方法10+::+DBD
的前1+: +DDC
等我得到的是这样的:
Problem is that in this method of sort "10" + "::" + "DBD"
are before "1" + "::" + "DDC"
etc I get something like:
0 :: ABC
,
10 :: DBD
,
1 :: DDC
,
22 :: DDD
,
2 :: DBC
和我需要的是:
0 :: ABC
,
1 :: DDC
,
2 :: DBC
,
10 :: DBD
,
22 :: DDD
在此我尝试做一些临时的整数列表,我得到的所有 ID
,排序此列表,在 my_list ,并从我的名单得到的名字,要明确这是code:
After this I try to make some temp integer list where i get all ID
, sort this list , compare numbers with spliced value in my_list
and get name from my list , to be clear this is code:
ArrayList<String> my_list = new ArrayList<String>();
ArrayList<String> sortedlist = new ArrayList<String>();
ArrayList<Integer> sortedTempIdlist = new ArrayList<Integer>();
my_list.add("0" + "::" + "ABC");
my_list.add("2" + "::" + "DBC");
my_list.add("1" + "::" + "DDC");
my_list.add("10" + "::" + "DBD");
my_list.add("22" + "::" + "DDD");
sortedTempIdlist(0);
sortedTempIdlist(2);
sortedTempIdlist(1);
sortedTempIdlist(10);
sortedTempIdlist(22);
Collections.sort(sortedTempIdlist);
for (int i = 0; i < sortedTempIdlist.size(); i++) {
String temp = my_list.get(i);
String[] s;
try {
s = temp.split("::");
String name = s[1].toString();
String id = s[0].toString();
for (String x : my_list) {
Integer compare = Integer.valueOf(String.valueOf(x.split("::")[0]));
if (sortedTempIdlist.get(i) == compare) {
sortedlist.add(String.valueOf(sortedTempIdlist.get(i)) + "::" + String.valueOf(x.split("::")[1]));
}
}
} catch (Exception e) {};
}
现在这项工作,并排序列表是确定的,但问题是,当我有很多列表成员这项工作要慢(可以说600或1000)。 有没有更快的方式是这样的?
Now this work and sort list is ok but problem is that this work to slow when i have to many list member(lets say 600 or 1000). Is there faster way for something like this?
感谢名单
推荐答案
裹的ID和一个小对象的字符串:
Wrap the id and the String in a small object:
public class Item {
public int id;
public String name;
}
和使用 Collections.sort()
对列表进行排序agains的ID:
and use Collections.sort()
to sort the list agains the id:
Collections.sort(listInstance, new Comparator<Item>() {
@Override
public int compare(Item lhs, Item rhs) {
return lhs.id < rhs.id ? - 1 : (lhs.id == rhs.id ? 0 : 1) ;
}
});
Collections.sort()
将整理您的列表O(nlogn)
相关推荐
最新文章