Carlton Jr. Carlton Jr. - 1 year ago 45
Java Question

Set<> inside of Map<>, print everything?

I want to read a

.txt
file, take all the words inside of that text and somehow print out how many times each words is in the text.

For example, take this text:

"A bright day a man walked into a bar and asked for a beer. He was denied the beer because he was a sheep"


Should give this:

5: a
2: he, beer
1: bright, day, walked, into, bar, asked, denied, was, the,because, man, and, for


Here is my code:

private void computeFrequencyMap() throws IOException {
TreeMap<String, Integer> dMap = new TreeMap<String, Integer>();
BufferedReader br = new BufferedReader(new FileReader(filen));
String line;
while( (line = br.readLine()) != null){
String [] words = line.split("\\s+");
for (String word : words) {
word = word.replaceAll("[^a-zA-Z]", "");
if (!dMap.containsKey(word.toLowerCase())) {
dMap.put(word.toLowerCase(), 1);
} else {
int count = dMap.get(word.toLowerCase());
dMap.put(word.toLowerCase(), count + 1);
}
}
}
TreeMap<Integer, HashSet<String>> sMap = new TreeMap<Integer, HashSet<String>>();
for (Map.Entry<String, Integer> entry : dMap.entrySet()) {
if(sMap.containsKey(entry.getValue())){
//sMap.put(entry.getValue(), entry.getKey());
}else{
sMap.put(entry.getValue(), new HashSet<String>());
}
}
for (Entry<Integer, HashSet<String>> entry : sMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}


This is what I get when I run the code:

1 []
2 []
3 []
4 []
5 []
6 []
7 []
8 []
9 []
10 []
11 []
12 []
14 []
16 []
18 []
27 []
32 []
33 []
38 []
44 []
54 []
71 []


I've only come so far, cant get the "add to the set" part right, any suggestions?

Answer Source

You forgot to actually add the words to the when you reverse the map:

Map<Integer, Set<String>> sMap = new TreeMap<>();
for (Map.Entry<String, Integer> entry : dMap.entrySet()) {
    Integer appearances = entry.getValue();
    Set<String> words = sMap.get(appearances);
    if (words == null) {
        words = new HashSet<>();
        sMap.put(appearances, words);
    }
    words.add(entry.getKey());
}