Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a List of Persons by first name, last name and so on?

Tags:

java

I'm prompting the user to enter his first name, last name and age.
I use a confirm dialog to ask user if he want's to add another person then I display the names that he entered.

How can I sort the persons by first name, second name and so on ?

public static void main(String[] args) {

    ArrayList<Person> list = new ArrayList();
    int i = 0;
    while (i == 0) {

        Person p = new Person();

        String fname = JOptionPane.showInputDialog("Enter First Name ");
        String lname = JOptionPane.showInputDialog("Enter Last Name ");
        int Age = Integer.parseInt(JOptionPane.showInputDialog("Enter your Age "));

        p.setfName(fname);
        p.setLname(lname);
        p.setAge(Age);

        list.add(p);


 i=JOptionPane.showConfirmDialog(null, "Are you Want to Add other person","Confirmation",2);

    }

    for (int j = 0; j < list.size(); j++) {
        System.out.print("First name : "+list.get(j).getfName()+"\t Last Name : " + list.get(j).getLname()+"\t Age : "+list.get(j).getAge());
    list.equals(j);

        System.out.print("\n------------------------ \n ");
}

public class Person{

    private String fName;
    private String lname;
    private int age;

    public Person() {

    }

    public Person(String fName, String lname, int age) {
        this.fName = fName;
        this.lname = lname;
        this.age = age;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}
like image 512
Mê D Ôo Avatar asked Nov 21 '25 00:11

Mê D Ôo


1 Answers

Two ways of doing it are, either have Person implement Comparable or use Comparator

Using Comparator:

Collections.sort(list, new Comparator() {

    public int compare(Object o1, Object o2) {
        String fn1 = ((Person) o1).getfName();
        String fn2 = ((Person) o2).getfName();

        int res = fn1.compareTo(fn2);
        if (res != 0) {
           return res;
        } else {
           String ln1 = ((Person) o1).getLName();
           String ln2 = ((Person) o2).getLName();
           return ln1.compareTo(ln2);
        }
});

(Just add this before your for loop)

You can figure out how to use Comparable yourself now

like image 81
Xipo Avatar answered Nov 23 '25 14:11

Xipo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!