Sorting maps without a comparator, an arraylist, or a treeset

こ雲淡風輕ζ 提交于 2019-12-24 15:37:57

问题


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. 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<>();

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

回答1:


If you ever change your mind about using basic JDK utilities, here's one way to do it with streams:

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



回答2:


You can't. HashMaps aren't ordered or sorted because the position of its elements are based on object hashes.

There are some good alternatives in this task Sort a Map<Key, Value> by values (Java).

Please, also check this one: What Java Collection should I use?



来源:https://stackoverflow.com/questions/36879295/sorting-maps-without-a-comparator-an-arraylist-or-a-treeset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!