Task: list all smartphones sorted by serial number (unique 4 int characters that appear at the beginning of each line) to the file. First you need to read them from the file. Question: how to sort the lines read from the file, only by the first four characters?

    1 answer 1

    You need Collections.sort and your Compartor

     ArrayList arrayList = new ArrayList(); //Add elements to Arraylist arrayList.add("1345245556"); arrayList.add("3346346245"); arrayList.add("5345442423"); arrayList.add("2234235436"); arrayList.add("4235346323"); IgnoreCaseComparator icc = new IgnoreCaseComparator(); Collections.sort(arrayList, icc); 

    The second argument of the Sort method is a comparator:

     class IgnoreCaseComparator implements Comparator<String> { public int compare(String strA, String strB) { //сравниваем не строки целиком, но только первые их 4 символа return strA.substring(0,4).compareToIgnoreCase(strB.substring(0,4)); } } 
    • Maybe this is a stupid question, but why strA and strB, and why are there two of them at once? - PoGostu
    • @PoGostu, the comparator compares all the lines in turn. But they can only be compared two at a time. As a result, the number according to prinip is more-less. As a result, all the lines are arranged in the order of these received numbers. Something like that) - YuriySPb
    • So, I understood it) And as the comparator is transferred to Collections.sort (arrayList, icc); ? - PoGostu
    • @PoGostu, well, so I wrote ... IgnoreCaseComparator icc = new IgnoreCaseComparator(); Collections.sort(arrayList, icc); IgnoreCaseComparator icc = new IgnoreCaseComparator(); Collections.sort(arrayList, icc); - Yuriy SPb
    • one
      You can immediately use the structure to store the sorted set, for example TreeSet and pass the Comporator as an argument to the constructor, then the compare () method will work every time you change the set, and adding new elements will not need to call the sort () method every time Aleksei Chibisov