Reputation:
I have File Names like :
and I want to sort it like :
Please help Me With some Ideas or codes
Upvotes: 0
Views: 54
Reputation: 122
One of the solutions is to use sort(List list, Comparator c)
See Collections.sort() using comparator? topic.
And code can look like:
public void sortFiles(BufferedReader fileReader) {
List<String> fileList = new ArrayList<String>();
String str;
try {
while ((str = fileReader.readLine()) != null) {
fileList.add(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Collections.sort(fileList, new ThisIsMyThing());
System.out.println("Sorted AS");
Iterator<String> fileNameIterator = fileList.iterator();
while (fileNameIterator.hasNext()) {
System.out.println(fileNameIterator.next());
}
}
class ThisIsMyThing implements Comparator<Object> {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
String[] l_side = s1.split("_");
String[] r_side = s2.split("_");
//Check if numbers are equal
if (l_side[0].equals(r_side[0])) {
if (l_side.length == r_side.length) {
return s1.compareTo(s2);
} else {
return l_side.length > r_side.length ? -1 : 1;
}
} else {
return s1.compareTo(s2);
}
}
}
Upvotes: 1