Joao Magalhães Joao Magalhães - 6 months ago 29
Java Question

Java - Sort Array List with Objects Alphabetically and Numerically

Im reading Classroom names ("B106") from a text file and saving them on a Array list.
I need to sort that Array by letter and then by number.
I read something about using Collections / Comparator but I wasnt able to implement them sucessfully, how can I do this?

Ex:
Input:
"B106", "D111", "A201", "B102"

Output:
"A201", "B102", "B106", "D111"

Class Core_Salas where I manage my files

public class Core_Sala {

//---------------------------------------------------------------------------
public static ArrayList<Sala> Sala = new ArrayList<Sala>();
private static File SF = new File("Salas.txt");
public static void LerSalas()
{

try
{
if(SF.exists()==true)
{
String[]parts;
Sala.clear();//Array list limpar
Scanner inputFile = new Scanner(SF);
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
Sala s1 = new Sala(line);
Sala.add(s1);
}
inputFile.close();
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
if(SF.exists()==false)
{
PrintWriter out = null;
try
{
out = new PrintWriter(SF);

}catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "O ficheiro de utilizadores estava danificado ou era inexistente, foi criado um novo com o utilizador admin!");
}
out.close();
}
}
}


Class Sala with getter Setter and Constructor

public class Sala {
private String Salas;

public Sala(String salas)
{
this.Salas=salas;
}
public String getSalas() {
return Salas;
}
public void setSalas(String salas) {
Salas = salas;
}

@Override
public String toString()
{
return Salas;
}
}

Answer

You can try this

 public static void main(String[] args) {
    LerSalas();
    Collections.sort(salaData, new Comparator<Sala>() {
        @Override
        public int compare(Sala o1, Sala o2) {
            return o1.getSalas().compareTo(o2.getSalas());
        }
    });
    salaData.stream().forEach(System.out::println);
}

let me know if it works for you