11 June 2017

Sắp Xếp Nhiều Trường Bằng Comparator @Override Compare trong Java

Student.java
Java Core 2017
package CompareSort; import java.util.Comparator; public class Student implements Comparator<Student> { private String name; private String address; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Student(String name, String address, int age) { super(); this.name = name; this.age = age; this.address = address; } public Student() { super(); } @Override public int compare(Student o1, Student o2) { int sizeName = o1.name.compareTo(o2.name); //Sort name (String) if (sizeName != 0) { return sizeName; } int sizeAddress = o1.address.compareTo(o2.address); //Sort Address (String) if (sizeAddress != 0) { return sizeAddress; } return o1.age - o2.age; //Sort Age (int) } }
Main.java
Java Core 2017
package CompareSort; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { Student a = new Student("A", "B", 6); Student b = new Student("C", "B", 5); Student c = new Student("C", "B", 3); Student d = new Student("A", "B", 1); Student e = new Student("C", "B", 4); Student f = new Student("A", "B", 7); ArrayList<Student> list = new ArrayList<Student>(); list.add(a); list.add(b); list.add(c); list.add(d); list.add(e); list.add(f); Collections.sort(list, new Student()); for (Student ss : list) { System.out.println(" Name: " + ss.getName() + " Address: " + ss.getAddress() + " Age: " + ss.getAge()); } } }
Trường hợp thay đổi giá trị thứ tự sắp xếp ưu tiên
Name > Address > Age
 Nếu Name trùng nhau thì sẽ ưu tiến sắp xếp theo Address


Nếu Name Address có tên trùng nhau thì ưu tiên cuối cũng sẽ sắp xếp theo Age

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang