我知道我可以使用 TreeMap 对 Map 进行排序,但我不知道如何按值排序,其中 id 是 ArrayList 的第一个索引。
这是代码:
public void sort()
{
Map<String, ArrayList<String>> m = new TreeMap<String,ArrayList<String>>();
String[] name = new String[]{"first name", "second name", "third name"};
String[] description = new String[]{"first description", "second description", "third description"};
String[] id = new String[]{"1", "2", "3"};
m.put(name[0], new ArrayList<String>(Arrays.asList(new String[]{description[0], id[0]})));
m.put(name[1], new ArrayList<String>(Arrays.asList(new String[]{description[1], id[1]})));
m.put(name[2], new ArrayList<String>(Arrays.asList(new String[]{description[2], id[2]})));
}
我尝试对 map 进行排序:
SortedSet<Map.Entry<String, ArrayList<String>>> sortedset = new TreeSet<Map.Entry<String, ArrayList<String>>>(
new Comparator<Map.Entry<String, ArrayList<String>>>()
{
public int compare(Entry<String, ArrayList<String>> o1, Entry<String, ArrayList<String>> o2)
{
// return Integer.valueOf(o1.getValue()[1]).compareTo(Integer.valueOf(o2.getValue()[1]));
return 0;
}
});
最佳答案
TreeMap accepts a custom comparator还。您需要创建一个自定义比较器并将其传递到 TreeMap 中:
// assuming you create mycomparator
Map<String, ArrayList<String>> m = new TreeMap<String,ArrayList<String>>(mycomparator);
关于Java 按映射中数组列表的第一个索引进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043003/