对象键值排序

时间:2013-06-07 12:53:50

标签: java sorting

我有一个ArrayList,其中包含CricketLiveScore的对象

  CricketLiveScore{
     String homeAbbrevation;
   }

   List myList=new ArrayList<CricketLiveScore>();
   CricketLiveScore c1=new CricketLiveScore();
   c1.setHomeAbbrevation("IND vs PAK");
   CricketLiveScore c2=new CricketLiveScore();
   c2.setHomeAbbrevation("SRI vs NWZ");
   CricketLiveScore c3=new CricketLiveScore();
   c3.setHomeAbbrevation("AUS vs BAN");
   CricketLiveScore c4=new CricketLiveScore();
   c4.setHomeAbbrevation("NWZ vs IND");

   list.add(c1);
   list.add(c2);
   list.add(c3);
   list.add(c4);

我需要在Object中对这个Arraylist进行排序,并在主页缩写中使用值IND 有人可以为此提供帮助,以便我需要一个列表进行排序,并显示输出包含IND的值。

5 个答案:

答案 0 :(得分:2)

试试这个:

public class CricketLiveScoreComparator implements Comparator<CricketLiveScore> {
    @Override
    public int compare(CricketLiveScore c1, CricketLiveScore c2) {
        return c1.getHomeAbbrevation().compareTo(c2.getHomeAbbrevation());
    }
}

然后调用排序操作:

Collections.sort(myList, new CricketLiveScoreComparator());

答案 1 :(得分:1)

  public class CricketSort implements Comparator<CricketLiveScore> {

    String countryOnTop;

    public CricketSort(String countryOnTop) {
        this.countryOnTop = countryOnTop;
    }

    @Override
    public int compare(CricketLiveScore o1, CricketLiveScore o2) {
        if (o1.homeAbbrevation.contains(countryOnTop)) {
            return -1;
        }
        if (o2.homeAbbrevation.contains(countryOnTop)){
            return 1;
        }
        return o1.homeAbbrevation.compareTo(o2.homeAbbrevation);
    }

    public static void main(String[] args) {
        // ....stuff
        Collections.sort(scoreList, new CricketSort("IND"));
    }

}

应该工作。

答案 2 :(得分:0)

答案 3 :(得分:0)

http://blog.vogella.com/2009/08/04/collections-sort-java/

基本上,您在数据类型中实现Comparator接口并覆盖比较方法。

答案 4 :(得分:0)

好的!得到了我自己的比较器

      class CricketSort implements Comparator<CricketLiveScore> 
     { 
        String countryOnTop; 

         public CricketSort(String countryOnTop) { 
                this.countryOnTop = countryOnTop;
       }

      @Override 
      public int compare(CricketLiveScore o1, CricketLiveScore o2) { 
             if (o1.homeAbbrevation.contains(countryOnTop)) {
                  return -1; 
                  } 
             if (o2.homeAbbrevation.contains(countryOnTop)) { 
                  return 1; 
                  } 
           return o1.homeAbbrevation.compareTo(o2.homeAbbrevation);
             } 
         }

    }

它非常适合我