Sắp xếp nâng cao LinkedList với ví dụ cụ thể

Giả sử chúng ta có một class Person chứa các thông tin: name, age, address, sex. Chúng ta dùng LinkedList để lưu trữ các Person này. 

// File Person.java 

public class Person {
    private String name;
    private String address;
    private int age;

    public Person(String name, String address, int age) {
        this.name = name;
        this.address = address;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", age=" + age +
                '}';
    }
}

Yêu cầu 1: xuất ra danh sách các Person sắp xếp tăng dần theo name.

import java_regex.Person;

import java.util.LinkedList;

public class Main {
    public static void main(String args[]) {
        LinkedList<Person> linkedList = new LinkedList<>();
        linkedList.add(new Person("a", "hcm", 19));
        linkedList.add(new Person("f", "hcm", 21));
        linkedList.add(new Person("k", "hcm", 23));
        linkedList.add(new Person("d", "hcm", 21));
        linkedList.add(new Person("s", "hcm", 20));
        linkedList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));

        linkedList.forEach(person -> System.out.println(person.toString()));
    }
}

Hoặc sử dụng Comparator

linkedList.sort(Comparator.comparing(Person::getName));

Output:

Person{name=’a’, address=’hcm’, age=19}
Person{name=’d’, address=’hcm’, age=21}
Person{name=’f’, address=’hcm’, age=21}
Person{name=’k’, address=’hcm’, age=23}
Person{name=’s’, address=’hcm’, age=20}

Yêu cầu 2: xuất ra danh sách các Person sắp xếp tăng dần theo name, nếu cùng name thì sắp xếp theo age.

 

import java_regex.Person;

import java.util.Comparator;
import java.util.LinkedList;

public class Main {
    public static void main(String args[]) {
        LinkedList<Person> linkedList = new LinkedList<>();
        linkedList.add(new Person("a", "hcm", 19));
        linkedList.add(new Person("f", "hcm", 21));
        linkedList.add(new Person("k", "hcm", 23));
        linkedList.add(new Person("a", "hcm", 21));
        linkedList.add(new Person("s", "hcm", 20));
        linkedList.sort(Comparator.comparing(o ->( (Person) o).getName())
                .thenComparing(o -> ((Person) o).getAge()));

        linkedList.forEach(person -> System.out.println(person.toString()));
    }
}

Output:

Person{name=’a’, address=’hcm’, age=19}
Person{name=’a’, address=’hcm’, age=21}
Person{name=’f’, address=’hcm’, age=21}
Person{name=’k’, address=’hcm’, age=23}
Person{name=’s’, address=’hcm’, age=20}

 

‹Previous Next›

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x