Alphabetically Sort an ArrayList [duplicate]

1

I have an ArrayList called Test with the fields:

public class Teste 
{
    private String dctitle;
    private String rdfabout;
    private String dbid;
    private String depto;
    private String sigla;
    private String ciclo;
    private String state;
    private String dataplanejadainicial;
    private String dataEntradaEstado;
    private String id;
    private String executante;
}

This ArrayList has N items and I need to create a method "OrderDept" which will receive as a parameter the ArrayList<Teste> teste and return me an ArrayList with the Tests ordered by Departments. Home I know I have a method called .sort but I do not know how to use it.


NOTE: in the Test class all the Get and Set attributes are implemented, I just did not put it so as not to leave the question too big     

asked by anonymous 10.10.2017 / 21:22

1 answer

1

Use Collections.sort with Interface Comparator to sort the same array , example minimum :

Teste a = new Teste();
a.setDepto("3");
Teste b = new Teste();
b.setDepto("2");
Teste c = new Teste();
c.setDepto("1");

ArrayList<Teste> testes = new ArrayList<>();
testes.add(a);
testes.add(b);
testes.add(c);


Collections.sort(testes, new Comparator(){
    @Override
    public int compare(Object o1, Object o2) {
        Teste a1 = (Teste)o1;
        Teste a2 = (Teste)o2;
        return a1.getDepto()
                .compareToIgnoreCase(a2.getDepto());
    }

});

or

Collections.sort(testes, new Comparator<Teste>(){
    @Override
    public int compare(Teste o1, Teste o2) {                
        return o1.getDepto()
                .compareToIgnoreCase(o2.getDepto());
    }
});

or

If you want to order even accented words:

Collections.sort(testes, new Comparator<Teste>(){
    private Collator collator = Collator.getInstance(Locale.US);            
    @Override
    public int compare(Teste o1, Teste o2) {    
        return getCollator().compare(o1.getDepto(), o2.getDepto());                
    }

    public Collator getCollator() {
        collator.setStrength(Collator.PRIMARY);
        return collator;
    }

});

Example ONLINE Ideone

References:

10.10.2017 / 21:34