【问题标题】:Compare list using a different variable if list items have the same value in one variable如果列表项在一个变量中具有相同的值,则使用不同的变量比较列表
【发布时间】:2020-05-08 08:25:58
【问题描述】:

我有一个 Person 类,其属性为 name (string) 和 age (int):

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

我创建了一个人员列表,并使用年龄进行了比较。

List<Person> persons = new ArrayList<>();
persons.add("Andrew", 18);
persons.add("Barry", 25);
persons.add("Cynthia", 33);
persons.add("Darwin", 33);

Collections.sort(persons, new Comparator<Person>() {
    @Override
    public int compare(Person lhs, Person rhs) {
        return lhs.getAge() < rhs.getAge() ? -1 : lhs.getAge() == lhs.getAge() ? 0 : 1;
    }
});

如果两个项目的年龄相同,我如何使用名称来比较它们?

【问题讨论】:

  • 向我们展示您当前的代码,我们可以告诉您如何扩展它。

标签: java android


【解决方案1】:

从 Java 8 开始,创建自定义 Comparator 要容易得多,并且可以比较多个字段。

您可以使用以下代码:

Comparator.comparing(Person::getAge).thenComparing(Person::getName)

就是这样。

您可以使用它对您的收藏进行排序,如下所示:

Collections.sort(filteredList, Comparator.comparing(Person::getAge).thenComparing(Person::getName))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2020-05-20
    • 2022-11-28
    相关资源
    最近更新 更多