1

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

1

1 Answer 1

1

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()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.