ArrayList 是一种对象的集合。它不像地图可以接受两个输入。
因此,有三种选择:
1.使用同时包含 Key 和 Map 并按 key 自动排序的 TreeMap 或
2。利用未排序的地图并使用比较器进行排序 - 请参阅 Sort a Map<Key, Value> by values (Java) 或
3。使用带有比较器的自定义类的数组列表。
-
1) 使用 TreeMap
树图是红黑树的一种实现。见:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html
TreeMap<Integer,String> countries = new TreeMap<Integer,String>();
countries.put(2, "India");
countries.put(1, "USA");
countries.put(3, "Pakistan");
Iterator<Entry<Integer, String>> it = countries.entrySet().iterator();
Entry<Integer, String> entry;
while(it.hasNext())
{
entry = it.next();
System.out.println(entry.getValue() + " " + entry.getKey());
}
这会产生:
USA 1
India 2
Pakistan 3
-
2) 使用未排序的地图并使用比较器进行排序
请参阅:Sort a Map<Key, Value> by values (Java),因为答案很会写。
-
3) 使用带有 Country 类的 ArrayList
为了支持您的示例,您需要创建一个 Country 类。
您需要执行以下操作:
- 在您的国家/地区类中实现 Comparable 并将比较逻辑放置在其中。
-
创建一个自定义比较器,将其提供给 Collection.sort 调用。
导入 java.util.ArrayList;
导入 java.util.Collections;
导入 java.util.InputMismatchException;
导入 java.util.Iterator;
公共类 CountrySortExample {
public static void main(String[] args) {
new CountrySortExample();
}
public ArrayList<Country> countries = new ArrayList<Country>();
public CountrySortExample()
{
countries.add(new Country("India",2));
countries.add(new Country("Pakistan",3));
countries.add(new Country("USA",1));
Collections.sort(countries);
Iterator<Country> it = countries.iterator();
Country count;
while(it.hasNext())
{
count = it.next();
System.out.println(count.CountryName + " " + count.CountryIndex);
}
}
class Country implements Comparable
{
public String CountryName;
public int CountryIndex;
public Country(String CountryName,int CountryIndex )
{
this.CountryName = CountryName;
this.CountryIndex = CountryIndex;
}
@Override
public int compareTo(Object o) {
if(! (o instanceof Country))
throw new InputMismatchException("Country is expected");
Country other = (Country)o;
if(other.CountryIndex > CountryIndex)
return -1;
else if(other.CountryIndex == CountryIndex)
return 0;
else return 1;
}
}
}
更多信息请访问:http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/