How to sort the name along with age in java

后端 未结 8 1199
失恋的感觉
失恋的感觉 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 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);
        }
    }
    

    }

提交回复
热议问题