How to sort the name along with age in java

后端 未结 8 1120
失恋的感觉
失恋的感觉 2021-01-17 23:34

I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.

For example my inp

相关标签:
8条回答
  • 2021-01-18 00:20

    // Sort Without using Comparator

    import java.util.ArrayList; import java.util.List;

    public class SortByNameThenAge {

    static class Student {
        String name;
        int age;
    
        public Student(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
    
    }
    
    public static void main(String[] args) {
        List<Student> olist = new ArrayList<>();
        olist.add(new Student("Sam", 26));
        olist.add(new Student("Sam", 22));
        olist.add(new Student("Abc", 25));
        olist.add(new Student("Abc", 22));
        olist.add(new Student("Abc", 23));
        olist.add(new Student("Sam", 24));
        olist.add(new Student("Sam2", 21));
        olist.add(new Student("Sam2", 19));
        // Order By name
        for (int i = 0; i < olist.size(); i++) {
            for (int j = olist.size() - 1; j > i; j--) {
                if (olist.get(i).name.compareTo(olist.get(j).name) > 0) {
                    Student temp = olist.get(i);
                    olist.set(i, olist.get(j));
                    olist.set(j, temp);
                }
            }
        }
    
        for (Student s : olist) {
            System.out.println(s.name + " : " + s.age);
        }
    
        // Order by name then age
        for (int i = 0; i < olist.size(); i++) {
            for (int j = i+1; j < olist.size(); j++) {
                if (olist.get(i).name.compareTo(olist.get(j).name) == 0) {
                    if (olist.get(i).age > olist.get(i + 1).age) {
                        Student temp = olist.get(i);
                        olist.set(i, olist.get(i + 1));
                        olist.set(i + 1, temp);
                    }
                }
            }
        }
        System.out.println("\nSorting by age keeping name as it is");
    
        for (Student s : olist) {
            System.out.println(s.name + " : " + s.age);
        }
    }
    

    }

    0 讨论(0)
  • 2021-01-18 00:21

    You are on the right path, but your compare method is incomplete.

    Since compare is called to decide which item in each pair is to go before the other, it must include all comparison logic, not only the tie-breaking one. Your code sorts on the age alone, ignoring the name completely.

    The logic should go like this:

    • Compare names using t.getFname().compareTo(t1.getFname())
    • If names are not the same, return the result of comparison
    • Otherwise, return the result of comparing ages.

    Proper way of comparing integers is with the static Integer.compare method, i.e. Integer.compare(t.getAge(), t1.getAge()).

    0 讨论(0)
提交回复
热议问题