Last active
November 27, 2016 15:12
-
-
Save yeedle/38e01f2924572399c40b42a5da455fd8 to your computer and use it in GitHub Desktop.
Counting occurrences of words or chars in a string using Java 8 streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.util.stream.*; | |
class CountingOccureences { | |
public static void main(String[] args) { | |
String example = "The quick brown fox jumps over the lazy dog and the dog catches the fox"; | |
System.out.println(countOccurences(example.replaceAll("\\s", ""), "")); | |
// output: {a=3, b=1, c=3, d=3, e=6, f=2, g=2, h=5, i=1, j=1, k=1, l=1, m=1, n=2, o=6, p=1, q=1, r=2, s=2, t=5, u=2, v=1, w=1, x=2, y=1, z=1} | |
System.out.println(countOccurences(example, " ")); | |
// output: {over=1, the=4, quick=1, and=1, lazy=1, catches=1, jumps=1, brown=1, dog=2, fox=2} | |
} | |
public static Map<String, Long> countOccurences(String s, String delim){ | |
return Arrays.stream(s.split(delim)) | |
.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment