In Android, I have a Set
, and I want to turn it into a sorted List
.
How to do it with Collections.sort()
?
protected List<PackageInfo> doInBackground(Void... params) {
Set<PackageInfo> adPackages = new HashSet<PackageInfo>();
//ArrayList<PackageInfo> adPackages = new ArrayList<PackageInfo>();
[..............]
return new ArrayList<PackageInfo>(adPackages);
//return adPackages;
}
List has a constructor which allows you to create it using any Collection. Then use the Collections.sort(List list) method.
Eg
Set<String> set = new HashSet<String>();
set.add("This is a unsorted set");
List<String> list = new ArrayList<String>(set);
Collections.sort(list); // or Collections.sort(list, Comparator);
Cheers.
This is not really an Android question. Look for java sort, comparator
. Here is a nice tutorial: http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
IMHO, I would use a SortedSet
instead of the standard Set
, and then use the addAll
method of the List
interface to convert the set (that is implicitly sorted) into a sorted list without having to do any sorting outside of the data structures.
Note that this will require that the objects stored within these data structures implement the Comparable
interface.
I think this might work for you
public void sortArrayPackage(ArrayList<PackageInfo> array)
{
Collections.sort(array, new Comparator<PackageInfo>(){
public int compare(PackageInfo o1, PackageInfo o2) {
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
String package1 = o1.packageName;
String package2 = o2.packageName;
return package1.compareTo(package2);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.