简体   繁体   English

对没有比较器,arraylist或treeset的地图进行排序

[英]Sorting maps without a comparator, an arraylist, or a treeset

After storing the words found on a web page and mapping them with their number of occurrences, how would you sort them by frequency(highest to lowest)? 存储网页上找到的单词并将其与出现次数进行映射后,您将如何按频率(从最高到最低)对它们进行排序?

The only imports I have access to are Arrays, HashMap, HashSet, Map, and Set. 我可以访问的唯一导入是Arrays,HashMap,HashSet,Map和Set。 I did research on how to do this but it seems like most people suggested using comparators or iterators, which I don't want to implement. 我研究了如何做到这一点,但似乎大多数人建议使用比较器或迭代器,我不想实现。

The map is set up as follows: Map found = new HashMap<>(); 地图设置如下:Map found = new HashMap <>();

Here's what I have so far: 这是我到目前为止所拥有的:

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

If you ever change your mind about using basic JDK utilities, here's one way to do it with streams: 如果您改变主意使用基本的JDK实用程序,这里有一种方法可以使用流:

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

You can't. 你不能。 HashMaps aren't ordered or sorted because the position of its elements are based on object hashes. HashMaps未排序或排序,因为其元素的位置基于对象哈希。

There are some good alternatives in this task Sort a Map<Key, Value> by values (Java) . 在此任务中有一些很好的替代方法按值(Java)对Map <Key,Value>进行排序

Please, also check this one: What Java Collection should I use? 请检查一下: 我应该使用什么Java Collection?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM