Nanabua
Nanabua

Reputation: 21

How to sort String in Arraylist

I have an ArrayList where I add customers. What i wnat to do is that i want to sort them, so they appear sorted on Console.

private static ArrayList <Kund> klista = new ArrayList<>();
Kund kundd = new Kund("a","b");
System.out.print("Namn: ");
String namn = scr.next();
System.out.print("Adress: ");  
String adress = scr.next(); 
if (!namnKontroll(namn)){
    System.out.println (namn + " " +"har lagts till \n");
    klista.add(kundd);
    Kund k = new Kund(namn, adress); 
    klista.add(k); 
}else{
    System.out.println("Kunden med det namnet finns redan i systemet!");
}

// this is how i add customers to my ArrayList. So now, how it is possible to sort those names in ArrayList. I want to sort them with Collections. thanks

Upvotes: 1

Views: 48

Answers (1)

Bruno Ribeiro
Bruno Ribeiro

Reputation: 6197

Try use Collections.sort(klista, theComparator). You will need create a Comparator, like this:

public class KundComparator implements Comparator<Kund> {

    @Override
    public int compare(Kund o1, Kund o2) {
        // write comparison logic here
        return o1.getID().compareTo(o2.getID());
    }

}

Then use the Comparator:

Collections.sort(klista, new KundComparator());

If you are using Java 8, you can do like this:

Collections.sort(klista, (Kund k1, Kund k2) -> k1.getId().compareTo(k2.getId()));

Upvotes: 1

Related Questions