Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Spliterators;
- import java.util.stream.StreamSupport;
- import static java.util.Comparator.comparingInt;
- import static java.util.Spliterator.*;
- import static java.util.function.Function.identity;
- import static java.util.stream.Collectors.toMap;
- public class StreamWordCounter {
- public static void main(String[] args) {
- Arrays.stream(args)
- .map(String::toLowerCase)
- .collect(toMap(identity(), Lexeme::new, Lexeme::merge))
- .values()
- .stream()
- .sorted(comparingInt(Lexeme::getCount).thenComparing(Lexeme::getWord))
- .limit(countWords)
- .map(Lexeme::getWord)
- .forEachOrdered(System.out::println);
- }
- private static class Lexeme {
- private final String word;
- private final int count;
- public Lexeme(String word, int count) {
- this.word = word;
- this.count = count;
- }
- public Lexeme(String word) {
- this.word = word;
- this.count = 1;
- }
- public String getWord() {
- return word;
- }
- public int getCount() {
- return count;
- }
- public Lexeme merge(Lexeme other) {
- return new Lexeme(word, count + other.count);
- }
- }
- }
Add Comment
Please, Sign In to add comment