java 如何使用集合对对象的属性进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5932720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:30:46  来源:igfitidea点击:

How to sort an attribute of an object using Collections

java

提问by newbie

Good day!

再会!

I have an object student with the following attributes:

我有一个具有以下属性的对象学生:

class Student
    String name
    Date birthday

I used arrayList to store the Student Objects My problem is, how can I sort the StudentList by birthday using the collecitons sort?.

我使用 arrayList 来存储学生对象我的问题是,如何使用集合排序按生日对学生列表进行排序?。

List <Student> studentList = new ArrayList<Student>();

How can I code it?

我该如何编码?

Collections.sort(????);

Collections.sort(????);

Thank you

谢谢

回答by WhiteFang34

You can pass a Comparatorto Collections.sort()to handle the sorting by birthday:

您可以传递一个ComparatortoCollections.sort()来处理按生日排序:

Collections.sort(studentList, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getBirthday().compareTo(s2.getBirthday());
    }
});

You'll need to add getBirthday()to your Studentclass if you don't have it already.

如果您还没有,则需要将其添加getBirthday()到您的Student课程中。

回答by Stefan Endrullis

In Java 8 you can sort the list with a one-liner using Lambda expressionsand Comparator.comparing:

在 Java 8 中,您可以使用Lambda 表达式Comparator对列表进行单行排序。比较

Collections.sort(studentList, Comparator.comparing(s -> s.getBirthday()));

Alternatively you can use the method reference:

或者,您可以使用方法参考:

Collections.sort(studentList, Comparator.comparing(Student::getBirthday));

回答by Ankit

Hi this is a sample that can help you to understand

嗨,这是一个可以帮助您理解的示例

package de.vogella.algorithms.sort.standardjava;

import java.util.Comparator;

public class MyIntComparable implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
    }
}


package de.vogella.algorithms.sort.standardjava;

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

public class Simple2 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(5);
        list.add(4);
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(1);
        Collections.sort(list, new MyIntComparable());
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
}

回答by Aaron Gage

You need to write a custom comparator.

您需要编写一个自定义比较器。

Something like:

就像是:

Collections.sort(studentList, new Comparator<Student>() {

    public int compare(Strudent a, Strudent b) {
        return a.birthday.compareTo(b.birthday);
    }

});

回答by sudmong

回答by bruno

This can be a tricky interview question :)

这可能是一个棘手的面试问题:)

The best and reusable way i've found to solve a similar problem was to implement the interface Comparator and also creating custom Comparator according to my needs, which can be reused.

我发现解决类似问题的最好和可重用的方法是实现接口 Comparator 并根据我的需要创建自定义 Comparator,可以重用。

I leave here an example how to sort an ArrayList of Person according to their name attribute and also according to their gender attribute (which don't have any lexicography natural order).

我在这里留下一个例子,如何根据他们的姓名属性和他们的性别属性(没有任何词典自然顺序)对 Person 的 ArrayList 进行排序。

The trick was defining a enum class with the custom attribute from which i wanted to sort. Applying a custom comparator to that enum attribute, the compareTo() method apply the order according to the natural order in which the values are declared (in this example male, female, others).

诀窍是使用我想要排序的自定义属性定义一个枚举类。将自定义比较器应用于该枚举属性,compareTo() 方法根据声明值的自然顺序(在此示例中为男性、女性、其他)应用顺序。

import java.util.*;

public class Person {

public enum Gender {
    male,female, others
}

String name;
int age;
Gender gender;

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

public String getName() {
    return name;
}

public Gender getGender() {
    return gender;
}

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

public static void printPersons(List<Person> personList) {

    for (int i = 0; i < personList.size(); i++) {
        System.out.println(personList.get(i).toString());
    }
}

public static void printSortedByAgePersons(List<Person> personList) {
    Collections.sort(personList, Person.COMPARE_BY_NAME);
    for (int i = 0; i < personList.size(); i++) {
        System.out.println(personList.get(i).toString());
    }
}

public static void printSortedByGender(List<Person> personList) {
    Collections.sort(personList, Person.COMPARE_BY_GENDER);
    printPersons(personList);
}

public static Comparator<Person> COMPARE_BY_NAME = new Comparator<Person>() {
    @Override
    public int compare(Person o1, Person o2) {
        return o1.getName().compareTo(o2.getName());
    }
};

public static Comparator<Person> COMPARE_BY_GENDER = new Comparator<Person>() {
    @Override
    public int compare(Person o1, Person o2) {
        return o1.getGender().compareTo(o2.getGender());
    }
};


// lets test this :
public static void main(String args[]) {

    Person p1 = new Person("André", 22, Gender.male);
    Person p2 = new Person("Minder", 19, Gender.others);
    Person p4 = new Person("Maria", 19, Gender.female);
    Person p3 = new Person("Pedro", 25, Gender.male);

    List<Person> personList = new ArrayList<Person>();
    personList.add(p1);
    personList.add(p2);
    personList.add(p3);
    personList.add(p4);

    System.out.println("original list:");
    printPersons(personList);

    System.out.println("------------------------------------------");
    System.out.println("sorted list by name in alphabetical order");
    printSortedByAgePersons(personList);

    System.out.println("------------------------------------------");
    System.out.println("sorted list by custom order(gender)");
    printSortedByGender(personList);

}

}