1

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++;
        }
    }
}
  • Are you sure you're not [Paul](http://stackoverflow.com/q/36871699/1553851)? – shmosel Apr 27 '16 at 02:46
  • 1
    *"...most people suggested using comparators or iterators..."* -- There's a reason for that -- *"...which I don't want to implement."* -- Why not? – azurefrog Apr 27 '16 at 02:47
  • If someone wants you to code without iterators, they're either a troll or they don't know what an iterator is. – shmosel Apr 27 '16 at 03:25

2 Answers2

0

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());
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

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?

Community
  • 1
  • 1
Jaumzera
  • 2,305
  • 1
  • 30
  • 44