如何对List< Object>进行排序按字母顺序使用对象名称字段 [英] How to sort a List<Object> alphabetically using Object name field

查看:584
本文介绍了如何对List< Object>进行排序按字母顺序使用对象名称字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像 List< Object>这样的对象列表p 。我想使用对象名字段按字母顺序对此列表进行排序。对象包含10个字段,名称字段是其中之一。

I have a List of Objects like List<Object> p.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is one of them.

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

但是没有像String.compare ..?

But there is nothing like String.compare..?

推荐答案

从您的代码看,您的 Comparator 已经参数化了运动。这仅适用于列表<广告系列> 。此外,您正在寻找的方法是 compareTo

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

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

或者如果您使用的是Java 1.8

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.

这篇关于如何对List&lt; Object&gt;进行排序按字母顺序使用对象名称字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆