Created
February 8, 2018 13:46
-
-
Save gfrison/3e130efeb0f17c7da59d78b520c34e96 to your computer and use it in GitHub Desktop.
a simple method for creating all possible n-grams of a given string
This file contains hidden or 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 static java.util.stream.IntStream.range; | |
import static java.util.stream.IntStream.rangeClosed; | |
private List<String> possibleNgrams(String[] words) { | |
return rangeClosed(1, words.length) | |
.mapToObj( | |
window -> | |
rangeClosed(0, words.length - window) | |
.mapToObj( | |
i -> | |
range(i, i + window) | |
.mapToObj(x -> words[x]) | |
.collect(Collectors.joining(" ")))) | |
.flatMap(Function.identity()) | |
.collect(Collectors.toList()); | |
} | |
System.out.println(possibleNgrams("pale ale beer".split("\\s+")) | |
> ["pale ale beer", "pale ale", "ale beer", "pale", "ale", "beer"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment