Skip to content

Instantly share code, notes, and snippets.

@EugenyB
Created April 22, 2021 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EugenyB/55b4cda3c84ca859318d706198724834 to your computer and use it in GitHub Desktop.
Save EugenyB/55b4cda3c84ca859318d706198724834 to your computer and use it in GitHub Desktop.
// Exercise 11: Gather the words into a map, accumulating a count of the
// number of occurrences of each word. Don't worry about upper case and
// lower case. Extra challenge: implement two solutions, one that uses
// groupingBy() and the other that uses toMap().
@Test
public void wordFrequencies() throws IOException {
// Map<String, Long> map = reader.lines()
// .flatMap(s -> Arrays.stream(s.split(REGEXP)))
// .filter(s -> !s.isEmpty())
// .collect(Collectors.groupingBy(s->s, Collectors.counting()));
Map<String, Long> map = reader.lines()
.flatMap(s -> Arrays.stream(s.split(REGEXP)))
.filter(s -> !s.isEmpty())
.collect(Collectors.toMap(s->s, s->1L, Long::sum));
assertEquals(2L, (long)map.get("tender"));
assertEquals(6L, (long)map.get("the"));
assertEquals(1L, (long)map.get("churl"));
assertEquals(2L, (long)map.get("thine"));
assertEquals(3L, (long)map.get("world"));
assertFalse(map.containsKey("lambda"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment