按属性对自定义对象排序

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.

I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class RandomName {
    ...
    Collections.sort(Database.arrayList, new CustomComparator);
    ...
}

转载于:https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property

0
csdnceshi66
必承其重 | 欲带皇冠 Answer by @Yishai in this post demonstrates elegant use of enum for custom sorting and grouped sorting (multiple arguments) utilizing comparator chaining.
接近 7 年之前 回复
csdnceshi60
℡Wang Yan Related: stackoverflow.com/questions/1814095/…
9 年多之前 回复

21个回答

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

26
csdnceshi66
必承其重 | 欲带皇冠 This solution does not work on Android API <24. Do you guys know a solution for this?
一年多之前 回复
csdnceshi59
ℙℕℤℝ Great example thanks
一年多之前 回复
weixin_41568208
北城已荒凉 If you are using Java 8, see if you can get rid of Date in favour of one of the new and more programmer frindly classes in the java.time package.
2 年多之前 回复
csdnceshi71
Memor.の The order of String sort is asc by default when use s1.compareTo(s2) and desc when use s2.compareTo(s1)
大约 3 年之前 回复
weixin_41568196
撒拉嘿哟木头 better yet, use List.sort().
3 年多之前 回复
csdnceshi60
℡Wang Yan O'Connor: it throws a NullPointerException.
3 年多之前 回复
csdnceshi68
local-host what happens when o1.getStartDate() returns null?
3 年多之前 回复
weixin_41568184
叼花硬汉 you can use to compare int values like this "return o1.getDistance()-o2.getDistance();"
接近 4 年之前 回复
csdnceshi60
℡Wang Yan I didn't specify whether the comparator was declared inside another class; if it is, then yes, you would want to make it static.
大约 5 年之前 回复
csdnceshi62
"幸运的战士" Comparator class should be static :)
大约 5 年之前 回复
weixin_41568110
七度&光 I think the answer best should also include the proper way to do it in Java 8. Collections.sort(list, Comparator.comparing(MyObject::getStartDate)); which reads better and is less error prone. It's very easy to write return o1.getStartDate().compareTo(o1.getStartDate());
5 年多之前 回复
csdnceshi74
7*4 +1 for mentioning that it should return int and that you'd better to use Date#compareTo() for this. Why this isn't upvoted above the other answer is beyond me. This link may also be useful: Object Ordering Tutorial at Sun.com.
9 年多之前 回复

For sorting an ArrayList you could use the following code snippet:

Collections.sort(studList, new Comparator<Student>(){
    public int compare(Student s1, Student s2) {
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
    }
});
25
weixin_41568131
10.24 That sorts but gives double value for each element
接近 3 年之前 回复
csdnceshi65
larry*wei Anybody using lambda stackoverflow.com/questions/2784514/…
接近 5 年之前 回复

New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()

Here is a code snippet which demonstrates the List.sort() feature:

List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));

// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]

// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));  
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]

The Fruit class is:

public class Fruit implements Comparable<Fruit>
{
private String name;
private String color;
private int quantity;

public Fruit(String name,String color,int quantity)
{ this.name = name; this.color = color; this.quantity = quantity;}

public String getFruitName() { return name; }        
public String getColor() { return color; }  
public int getQuantity() { return quantity; }

@Override public final int compareTo(Fruit f) // sorting the color
{
    return this.color.compareTo(f.color);
}     
@Override public String toString()
{   return (name + " is: " + color);
}

} // end of Fruit class

10

Since technologies appear everyday, the answer will change in the time. I took a look at LambdaJ and seems very interesting.

You can try solving these tasks with LambdaJ. You can find it here: http://code.google.com/p/lambdaj/

Here you have an example:

Sort Iterative

List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
           return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
        }
});

Sort with lambda

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

Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?

9
csdnceshi60
℡Wang Yan I had to remove even items in a foreach loop other wise it gives me double of each content.
接近 3 年之前 回复
weixin_41568174
from.. it shouldn't... it's working as expected. Unless you are using a new version with a bug, which I recommend you to post it in the forum. Anyway, this answer was post prior to java 8, if you use it, then it will much better than using lambdaj
接近 3 年之前 回复
csdnceshi60
℡Wang Yan That sorts but gives double value for each element how to avoid it
接近 3 年之前 回复

Java 8 Lambda shortens the sort.

Collections.sort(stdList, (o1, o2) -> o1.getName().compareTo(o2.getName()));
9
weixin_41568131
10.24 Collections.sort(stdList, Comparator.comparing(SomeClass::getName));
接近 4 年之前 回复

You can Sort using java 8

yourList.sort(Comparator.comparing(Classname::getName));

or

yourList.stream().forEach(a -> a.getBObjects().sort(Comparator.comparing(Classname::getValue)));
9

I prefer this process:

public class SortUtil
{    
    public static <T> List<T> sort(List<T> list, String sortByProperty)
    {
            Collections.sort(list, new BeanComparator(sortByProperty));
            return list;
    }
}

List<T> sortedList = SortUtil<T>.sort(unsortedList, "startDate");

If you list of objects has a property called startDate, you call use this over and over. You can even chain them startDate.time.

This requires your object to be Comparable which means you need a compareTo, equals, and hashCode implementation.

Yes, it could be faster... But now you don't have to make a new Comparator for each type of sort. If you can save on dev time and give up on runtime, you might go with this one.

9
weixin_41568208
北城已荒凉 1, this answer was given 2 hours earlier with working code provided as well. There is no need to repost the same solution and clutter the forum especially since BeanComparator is not a standard class, so its not really a solution if the poster doesn't know what you are talking about. If you like the original suggestion you can upvote it and add a comment if you wish.
9 年多之前 回复

You can have a look into this presentation hold at the Java Forum in Stuttgart Germany in 2016.

Only a few slides use German language, 99% of the content is "English based" Java source code; like

someCollection.sort(
  OurCustomComparator
    .comparing(Person::getName)
    .thenComparing(Person::getId)
);

where OurCustomComparator is using default methods (and other interesting ideas). As shown, leading to very concise code to pick some getter method for sorting; and super simple chaining (or reversing) of sort criteria.

If you are into java8, you find a lot of material there to get you started.

8

From Java 8 and onward we don't have to use Collections.sort() directly. List interface has a default sort() method:

List<User> users = Arrays.asList(user1,user2,user3);
users.sort( (u1, u2) -> { 
return u1.getFirstName.compareTo(u2.getFirstName());}); 

See http://visvv.blogspot.in/2016/01/sorting-objects-in-java-8.html.

7

For Java 8:

Collections.sort(list, comparing(ClassName::getName));

or

Collections.sort(list, comparing(ClassName::getName).reversed());

Another way is

Collections.sort(list, comparing(ClassName::getName, Comparator.nullsLast(Comparator.naturalOrder())));
7
共21条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!