Reputation: 221
First to say that I see very similar questions but i think this is not duplicate.
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);
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
And what i need is :
0::ABC
,
1::DDC
,
2::DBC
,
10::DBD
,
22::DDD
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) {};
}
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?
Thanx
Upvotes: 1
Views: 494
Reputation: 157487
Wrap the id and the String in a small object:
public class Item {
public int id;
public String name;
}
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()
will sort your list in O(nlogn)
Upvotes: 2