I'm trying to sort filenames that's in fList array. Originally fList is sorted like this https://i.sstatic.net/OCqJR.jpg and after result https://i.sstatic.net/GgBsq.jpg
I wanted the result sorted according to their preceding number before the filename like so:
- Selenium Introduction
- Complete Installation Guide for java and Selenium Learning
- Brush up Java Concepts for Selenium Automation
- CORE JAVA In depth for Manual testers and Beginners
...
- Bonus!! Student Special
I have something() method to get the number from fList[x] filename to later compare when doing the swap(fList[x], fList[y]) as you can tell from output console.
I'm not sure I understand how File[] actually stores and changes its elements
public static void main(String[] args) {
File file = new File("pathToFolder");
File[] fList = file.listFiles();
for(int x = 0; x < fList.length; x++) {
int numberX = something(fList[x]);
for(int y = x; y < fList.length; y++) {
int numberY = something(fList[y]);
if(numberX > numberY) {
File temp = fList[x];
fList[x] = fList[y];
fList[y] = temp;
}
}
}
for(int x = 0; x < fList.length; x++) {
System.out.println(fList[x].getName());
}
}
static int something(File file) {
String temp = file.getName();
String number = "";
for(int st = 0; st < temp.length(); st++) {
if(temp.charAt(st) == '.') break;
number += temp.charAt(st);
}
int fileNumber = Integer.parseInt(number);
return fileNumber;
}
numberXbut not updating it when you swap.somethingmethod into aComparator.comparemethod?Arrays.sort( fList, Comparator.comparing( File::getName, Comparator.comparingInt( name -> Integer.parseInt( name.split("\\.")[0] ) ) ) )OR using yoursomethingmethodArrays.sort( fList, Comparator.comparingInt(YourClassName::something) );