【问题标题】:Sort ArrayList based on a on object property根据对象属性对 ArrayList 进行排序
【发布时间】:2014-05-05 08:40:26
【问题描述】:

我有一个ArrayList<CustomObject> myFinalList = new ArrayList<CustomObject>(); 该列表对列表中的每个条目都有一个 ojbect 属性“NumberOfLikes”。 "NumberOfLikes" 是字符串值。

我已经将这些值派生到一个数组中,如下所示:-

ArrayList<String> numberOfLikes = new ArrayList<String>();

        for(int j =0; j<myFinalList.size(); j++)
        {
            String likes = myFinalList.get(j).getNewsLikes();
            numberOfLikes.add(likes);
        }


        numberofLikesArray=  numberOfLikes.toArray(new String[numberOfLikes.size()]);

    int[] numberofLikesArrayInt = new int[numberofLikesArray.length];

    for (int n = 0; n < numberofLikesArray.length; n++) 
    {
        numberofLikesArrayInt[n] = Integer.parseInt(numberofLikesArray[n]);
    }
    Arrays.sort(numberofLikesArrayInt);
    ArrayList<Integer> intAarrylistlikes = new ArrayList<Integer>();
    for (int i = 0; i < numberofLikesArrayInt.length; i++) 
    {
        intAarrylistlikes.add(numberofLikesArrayInt[i]);
    }
    Collections.reverse(intAarrylistlikes);
    numberofLikesArrayInt = convertIntegers(intAarrylistlikes);
    numberofLikesArray = Arrays.toString(numberofLikesArrayInt).split("[\\[\\]]")[1].split(", ");

    for (int i = 0; i < numberofLikesArray.length; i++) 
    {
        companyNewsList = Lists.newArrayList(Collections2.filter(myFinalList, new ArticleFilter2(numberofLikesArray[i])));
    }

ArticleFilter2.java

public class ArticleFilter2 implements Predicate<News>
{
    private final Pattern pattern;

    public ArticleFilter2(final String regex)
    {
        pattern = Pattern.compile(regex);
    }

    @Override
    public boolean apply(final CustomObject input)
    {
        return pattern.matcher(input.getLikes()).find();
    }
}

现在这个数组由“NumberOfLikes”按降序排列。现在我想创建另一个 ArrayList,它根据这些值对“MyFinalList”进行排序,即:- 具有最大喜欢的项目应该首先出现。

我该怎么做?

【问题讨论】:

  • 是否可以为 CumstomObject 类添加 numberOfLikes 的属性(getter 和 setter)?
  • @Bob 是的。我已经设置了 getter 和 setter
  • 然后就可以使用AndroidGuys awnser对列表进行排序了。

标签: java android arrays sorting arraylist


【解决方案1】:

这要求Comparator 与您的自定义类。 http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

新建一个实现 Comparator 的类并实现这个方法:

public class YourComparator<CustomClass> implements Comparator{
    @Override
    public int compare ( CustomClass obj1, CustomClass obj2 ) {
        return (int) (obj1.getYourProperty() - obj2.getYourProperty());
    }
}

使用它:

Collections.sort(MyFinalList, new YourComparator());

【讨论】:

  • 我要对 List 进行排序的属性是一个字符串
  • 这个列表是什么类型并不重要。在 compare 方法中,您可以对这些字符串值实现自己的比较逻辑。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多