使用来自不同类的变量对列表进行排序:Android

时间:2017-07-04 13:02:00

标签: android sorting collections

我有一个班级,

public class ACompanyForSearchResult {
String companyName;
int likes;
}

以及它的清单:

 ArrayList<ACompanyForSearchResult> List = new ArrayList<ACompanyForSearchResult>();

我在这里按名称排序,

/*To get the sorted value by name*/
private void sortName() {
Collections.sort(List, new Comparator<ACompanyForSearchResult>() {
     @Override
    public int compare(ACompanyForSearchResult aCompanyForSearchResult, ACompanyForSearchResult t1) {
            return (aCompanyForSearchResult.companyName).compareToIgnoreCase(t1.companyName);
        }
    });
  }
}

现在我希望数据按照不同类BranchDetails中的城市名称进行排序,

public class BranchDetails {
  String cityName;
}

我想使用此cityName对上面的“List”进行排序。但是我无法将cityName访问到上一课程。我是新手,所以请耐心等待。

1 个答案:

答案 0 :(得分:0)

实施比较器:

   MyComparator extend  Comparator{
   Map<String ,String>  mMap=new HashMap();  key is  city, value is company


 public int  compare(BranchDetails  a , BranchDetails   b){
     if( mMap.get(a.cityName).compareto(mMap.get(b.cityName))==0){
     return a .cityName.compareto(b.cityName);
}else {
     return mMap.get(a.cityName).compareto(mMap.get(b.cityName));
}

}