Reputation: 425
I have been successful in sorting Arraylist of files using the following code :
Comparator<File> stringLengthComparator = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Integer.compare((int) (o1.length() / 1000),
(int) (o2.length() / 1000));
}
};
Collections.sort(flLst, stringLengthComparator);
This sorts the file list i.e. flLst, but the only issue is the above code requires API level 19 and above and my current API minimum requirement is API level 9. I tried the following but I am unable to swap files :
for(x=0;x<flLst.size();x++)
val1=flLst.get(x);
for(x=0;x<flLst.size();x++)
{
for(int j=i;j<flLst.size();j++)
{
if(val1.length()>flLst.get(j).length())
{
temp=val1;
val1=flLst.get(j);
flLst.get(j)=temp; // I get issue here as swapping file variables is not allowed this way
}
}
}
Is there a solution for API level 9 that I can use.
Upvotes: 0
Views: 1154
Reputation: 414
Fast and easy compare by size:
Arrays.sort(fileList, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
return Long.compare(f1.length(), f2.length());
// For descending
// return -Long.compare(f1.length(), f2.length());
}
});
Upvotes: 0
Reputation: 93561
Comparator<File> stringLengthComparator = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.length() - o2.length();
}
};
Your solution was just making things way overcomplicated.
Upvotes: 0
Reputation: 1803
As mentioned in the docs, Integer's compare() method:
Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
So in your case, try the following instead which was added in API level 1:
Comparator<File> stringLengthComparator = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Integer.valueOf((int) (o1.length() / 1000)).compareTo(Integer.valueOf((int) (o2.length() / 1000)));
}
};
Upvotes: 1