Reputation: 1710
I need to sort this array with filename, each item is from different path.
how do i sort this array based on file names.
ArrayList<String> sort = new ArrayList<>();
sort.add("/etc/fest/gerts.png");
sort.add("/etc/fest/ase.png");
sort.add("/etc/test/zer.png");
sort.add("/etc/fest/dse.png");
Upvotes: 2
Views: 2694
Reputation: 3709
You can do something like this in Java 8:
Here in this it will first get the file names by substringing the string based on last index of "/". And then sort based on the same.
list.sort(Comparator
.comparing(s -> s.substring(s.lastIndexOf("/") + 1))
In case you are not on Java 8.
You can create a custom Comparator like this and then call the Collections
API.
public class SubstringComparator implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = o1.tostring().substring(o1.tostring().lastIndexOf("/") + 1);
String s2 = o2.tostring().substring(o2.tostring().lastIndexOf("/") + 1);
return s1.compareTo(s2);
// or, more concisely:
// return o1.toString().substring(1).equals(o2.toString().substring(1));
}
}
And then call it as below:
SubstringComparator comparator = new SubstringComparator();
Collections.sort(list, comparator );
Upvotes: 2
Reputation: 7709
This will sort only by the file names, ignoring the parent folders:
Using JAVA 8
sort.sort(Comparator.comparing(o -> new File(o).getName().toUpperCase()));
sort.forEach(System.out::println);
Using JAVA < 8
sort.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return new File(o1).getName().toUpperCase().compareTo(new File(o2).getName().toUpperCase());
}
});
for (String s : sort) {
System.out.println(s);
}
This will produce the following output:
/etc/fest/ase.png
/etc/fest/dse.png
/etc/fest/gerts.png
/etc/test/zer.png
Upvotes: 1
Reputation: 2476
you can use the Collection method sort
Collections.sort(sort);
Upvotes: 0