Java java.util.Map.Entry和Collection.sort(List,Comparator)

时间:2014-01-14 03:10:07

标签: java dictionary collections comparator

我在java中做了一些execrices,我必须从文件中读取单词,然后 将此单词放入Map类型Hashmap(word<String,Integer>)。一切都完成了。

下一组对(类型为java.util.Map.Entry),保存到List(List<Entry<String,Integer>>)中,然后按Collections.sort(List,Comparator)对其进行排序。 但它不起作用,因为它说排序不合适,我没有这么多经验,有人可以帮助我在这个当前的例子中如何? ...谢谢你的帮助。

代码中有一部分:

public static void Reader(){

   class Word{
    private String key;     
    private int value;


    public int getValue(){
        return value;
    }

    public void setValue(){
        value=this.value;
    }

    public String getKey(){
        return key;
    }

    public void setKey(){
        key=this.key;
    }

    public Word(String key,Integer value){
        this.key= key;
        this.value = value;

    }
    public Word(){

    }

  }

    Map<String, Integer> wordsmap = new HashMap<String, Integer>();
        wordsmap.put("car",2); // wordsmap.put(word as key,frequency as value)
        wordsmap.put("bike",6);
        wordsmap.put("like",1);

       List<Entry<String,Integer>> words = new ArrayList<>(wordsmap.entrySet());

       Collections.sort(words,new Comparator<Word>(){
       public int compare(Word o1,Word o2){
           return o1.getValue() - o2.getValue();
       }

   });
  }


 public static void main(String[] args) {

        Reader();
    }

1 个答案:

答案 0 :(得分:2)

您使用List<Entry<String, Integer>>对<{1}}进行排序:

Comparator<Entry<String, Integer>>

您尚未说明如何比较条目:我比较了键,但您可以按照自己喜欢的方式计算比较。


Java 8更新,使用lambda而不是匿名类:

Collections.sort(seznam, new Comparator<Entry<String, Integer>(){
   public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2){
       return o1.getKey().compareTo(o2.getKey()); // for example
   }
});