【问题标题】:Sorting maps without a comparator, an arraylist, or a treeset在没有比较器、数组列表或树集的情况下对地图进行排序
【发布时间】:2016-04-27 02:38:17
【问题描述】:

存储在网页上找到的单词并将它们与其出现次数进行映射后,您将如何按频率(从高到低)对它们进行排序?

我可以访问的唯一导入是 Arrays、HashMap、HashSet、Map 和 Set。我对如何做到这一点进行了研究,但似乎大多数人建议使用比较器或迭代器,我不想实现。

地图设置如下:Map found = new HashMap();

这是我目前所拥有的:

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import util.WebDoc;

public class Sorting{

public static void main(String[] args) throws IOException {
String url;

url = “INSERT URL HERE”;

final int numPairs = 30; // maximum number of pairs to print

// get body of the web document
String content = WebDoc.getBodyContent(url); 
String word_pattern = "[A-Za-z]{5,}";
Map<String, Integer> found = new HashMap<>(); // (word,frequency)

Matcher match = Pattern.compile(word_pattern).matcher(content);
int unique = 0;
while (match.find()) {
  String word = match.group().toLowerCase();

  System.out.println(word);  

        if (found.containsKey(word)){
            if (found.get(word)==1)
               unique--;
            found.put(word, found.get(word) +1);
        }
        else{ 
            found.put(word, 1);
            unique++;
        }
    }
}

【问题讨论】:

  • 你确定你不是Paul?
  • "...大多数人建议使用比较器或迭代器..." -- 这是有原因的 -- "...我不这样做不想实施。” -- 为什么不呢?
  • 如果有人想让你在没有迭代器的情况下编写代码,那么他们要么是巨魔,要么不知道迭代器是什么。

标签: java hashmap


【解决方案1】:

如果您改变了使用基本 JDK 实用程序的想法,这里有一种使用流的方法:

List<String> sorted = found.entrySet()
        .stream()
        .sort(Comparator.comparing(Map.Entry::getValue).reversed())
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    你不能。 HashMap 没有排序或排序,因为其元素的位置基于对象哈希。

    这个任务Sort a Map<Key, Value> by values (Java)有一些不错的选择。

    请也检查一下这个:What Java Collection should I use?

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      相关资源
      最近更新 更多