How to sort a List<Object> alphabetically using Object name field

后端 未结 16 1420
暗喜
暗喜 2020-11-28 06:00

I have a List of Objects like List p.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is o
16条回答
  •  醉梦人生
    2020-11-28 06:16

    This is assuming a list of YourClass instead of Object, as explained by amit.

    You can use this bit from the Google Guava library:

    Collections.sort(list, Ordering.natural()
      .onResultOf(new Function() {
      public String call(YourClass o) {
         return o.getName();
      }))
      .nullsLast();
    

    The other answers which mention Comparator are not incorrect, since Ordering implements Comparator. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".

    Copied shamelessly from this answer on my own question.

提交回复
热议问题