Sorting ArrayList of Objects by Object attribute

前端 未结 2 644
南旧
南旧 2020-12-01 13:15

I am having an Arraylist of Objects. Those object have an attribute or datatype - \'String\'. I need to sort the Arraylist by that string. How to achieve this?

2条回答
  •  有刺的猬
    2020-12-01 14:05

    You need to write a Comparator and use Collections.sort(List, Comparator to sort your List.

    Or else, your MyObject can also implements Comparable, defining a natural ordering that compares on your specific attribute, and then use Collections.sort(List instead.

    See also

    • Java Tutorials/Object Ordering

    Related questions

    On sorting List on various criteria:

    • Sorting an ArrayList of Contacts

    On Comparator and Comparable

    • When to use Comparable vs Comparator
    • difference between compare() and compareTo()
    • Comparable and Comparator contract with regards to null
    • Why does the Java Collections Framework offer two different ways to sort?

提交回复
热议问题