Java Sorting: sort an array of objects by property, object not allowed to use Comparable

后端 未结 4 686
生来不讨喜
生来不讨喜 2020-12-01 11:30

I have a class, Library, that contains an array of Book objects, and I need to sort the array based off the properties of Book, either Title or PageNumber. The problem is im

4条回答
  •  醉酒成梦
    2020-12-01 11:54

    Expanding @PeterLawrey's answer to Java 8, you can now use a Lambda Expression instead of a Comparable delegate:

    Collections.sort(books, (firstBook, secondBook -> b1 is greater return +1, 
                                                      if b2 is smaller return -1 otherwise 0));
    

提交回复
热议问题