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

后端 未结 16 1424
暗喜
暗喜 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:27

    From your code, it looks like your Comparator is already parameterized with Campaign. This will only work with List. Also, the method you're looking for is compareTo.

    if (list.size() > 0) {
      Collections.sort(list, new Comparator() {
          @Override
          public int compare(final Campaign object1, final Campaign object2) {
              return object1.getName().compareTo(object2.getName());
          }
      });
    }
    

    Or if you are using Java 1.8

    list
      .stream()
      .sorted((object1, object2) -> object1.getName().compareTo(object2.getName()));
    

    One final comment -- there's no point in checking the list size. Sort will work on an empty list.

提交回复
热议问题