0

So far, i have figured out how to get all the words to show, alongside the number which indicates how many times each unique word appears in the text. However, i cannot figure out how to get another list which displays all the unique words that ONLY occur 4 or more times. Any idea on how i can achieve this because i think i have done the hard bit here, but i would just like to know how i can get this next part.

A.Adams
  • 65
  • 2
  • 8

2 Answers2

2

With Java 8 you can use stream and filter by value:

System.out.println("List of unique word occurrences: " +
    countOcc.entrySet().stream()
.filter(e -> e.getValue() >= 4)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

Or instead of collecting to another Map just print out or collect into List instead:

    .map(e -> e.getKey())
.collect(Collectors.toList());
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
  • 1
    @A.Adams : There are other ways how to achieve this but generally the pattern is the same. You can use for loop over entrySet() instead and compare the getValue() manually. But the complexity remains the same. – Zbynek Vyskovsky - kvr000 Feb 07 '17 at 03:05
1

Assuming that you are using Java 8, you can filter the entries in the countOcc map as follows based on the number of occurrences in the text. Finally, I have printed the filtered results.

countOcc.entrySet().stream()
    .filter(entry->entry.getValue()>=4)
    .forEach(entry->System.out.println(entry.getKey()))
Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34
  • 1
    You can do the same with a `for(Map.Entry entry : countOcc.entrySet())` and checking if `entry.getValue()>=4` inside the for loop with an if condition. – Imesha Sudasingha Feb 07 '17 at 03:04