【问题标题】:Java java.util.Map.Entry and Collection.sort(List,Comparator) [closed]Java java.util.Map.Entry 和 Collection.sort(List,Comparator) [关闭]
【发布时间】:2014-01-14 03:10:07
【问题描述】:

我在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();
    }

【问题讨论】:

  • @brianRoach 谢谢你的时间,但我知道,有 java 文档和数百个例子。我正在寻找可以在此示例中进行解释的人,而不是发送链接。但也谢谢你。
  • 您的代码不起作用/没有意义。为什么要创建一个您不使用的 slova 类和一个您使用的 slova 变量?为什么你使用word1 和其他人却没有定义它们?
  • @nathanielwaisbrot 是 word1 的错误,意思是我会在 map 中放入一些在文本中出现频率的词,例如 slova.put("car",5) 。我会修理它。对于 slova 类,我正在使用 getValue() ...但是当然,我看到了许多比较器的示例,我不知道如何在我的示例中使用它,所以我尝试了一些,并且还有 slova 类。接下来要做什么才能使这个比较器起作用?谢谢...
  • 你的代码还是很乱。我建议在尝试进一步学习之前与讲师交谈或阅读一些有关 Java 的介绍性文本。

标签: java dictionary collections comparator


【解决方案1】:

您将List&lt;Entry&lt;String, Integer&gt;&gt;Comparator&lt;Entry&lt;String, Integer&gt;&gt; 排序:

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
   }
});

你没有说明你想如何比较条目:我已经比较了键,但是你可以计算你喜欢的比较。


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

Collections.sort(seznam, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));

【讨论】:

  • @Serġan 我添加了一个 lambda 版本(发布此答案时尚不可用)。
  • 顺便说一句,这个问题目前计划作为 [entry] burnination 的一部分被删除 - 这个问题应该保留吗?
  • @EJoshuaS 它不应该有条目标签,我已将其删除。
猜你喜欢
  • 1970-01-01
  • 2018-10-03
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
相关资源
最近更新 更多