通过两个不同的属性对ArrayList进行排序

时间:2014-11-15 20:09:57

标签: arraylist hashmap

所以我有一个HashMap<String, Integer>表示在一个句子中遇到某个单词的次数。我想要做的是将所有单词放在ArrayList<String>中,首先按一个单词遇到的次数排序,然后按字母顺序打破联系。我该怎么做呢?我的代码看起来像这样:

public class MyClass {
    private HashMap<String, Integer> map;
    public ArrayList<String> Order() {
         ArrayList<String> temp = new ArrayList<>();
         (...)
    }

1 个答案:

答案 0 :(得分:0)

您需要使用自定义比较器。对于比较方法,如果第一个参数应被视为小于第二个参数,则需要返回负值,如果它们相等则需要返回0,如果第一个参数应被视为大于第二个参数,则需要返回正值。

请注意,这会根据整数值

按降序对ArrayList进行排序
import java.util.Comparator;
import java.util.HashMap;

public class CustomComparator implements Comparator<String>
{
    HashMap<String, Integer> map;

    public CustomComparator(HashMap<String, Integer> comparisonMap)
    {
        map = comparisonMap;
    }

    @Override
    public int compare(String s1, String s2)
    {
        int count1 = map.get(s1);
        int count2 = map.get(s2);

        if (count1 == count2)
            return s1.compareTo(s2);
        return count2 - count1;
    }
}

创建和排序ArrayList的两个步骤:

首先,将HashMap中的每个键添加到ArrayList

ArrayList<String> result = new ArrayList<String>(map.size());
result.addAll(map.keySet());

然后,使用自定义比较器对ArrayList进行排序:

Collections.sort(result, new CustomComparator(map));