简体   繁体   English

根据没有比较器的成员变量的顺序对对象进行排序

[英]Order objects based on ordering of member variables without comparator

Say I have an object 说我有一个对象

Person
  private int age;
  private String name;

And I want to sort them automatically using something like Arrays.sort() such that low ages come before high ages. 我想使用Arrays.sort()类的东西对它们进行自动Arrays.sort() ,以使低龄出现在高龄之前。

A common way to do this is with a comparator, but I with so many useful utility functions out there, is there a cleaner way to do this? 常用的方法是使用比较器,但是我那里有许多有用的实用程序功能,是否有更干净的方法可以做到这一点?

使您的班级实现Comparable

lambdaj的示例解决了您的用例:

List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge());

Using Java 8 with Lambda: 将Java 8与Lambda结合使用:

personList.sort((p1, p2) -> Integer.compare(p1.age, p2.age));

or 要么

Collections.sort(personList, (p1, p2) -> Integer.compare(p1.age, p2.age));

Mistakes were made 犯了错误

You can also implement the interface Comparable and override the compareTo(...) method. 您还可以实现接口Comparable并重写compareTo(...)方法。

These ways to not guarentee it will be cleaner, but they are just different ways to compare. 这些不能保证其清洁的方法,但是它们只是比较的不同方法。 Using Comparator is only useful when you want to order objects in such a way that does not follow it's natural order. 仅当您要以不遵循自然顺序的方式对对象进行排序时,使用Comparator才有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM