Home How do I write below code in Java 8 using Stream API?
Reply: 0

How do I write below code in Java 8 using Stream API?

user6508
1#
user6508 Published in September 19, 2018, 9:27 am

Is there any way to write the following code using Streams?

public Map<String, Integer> process() {
    List<String> words = Arrays.asList(message.toLowerCase().split("[?.\\s]+"));
    Map<String, Integer> countMap = new HashMap<>();

    for (String word : words) {
        if (word.length() > 2) {
            Integer count = countMap.getOrDefault(word, 0);
            countMap.put(word, count + 1);
        }
    }
    return countMap;
}
share|improve this question
  • I just wanted to count words which are have greater than 2 characters. – Ashlin Karkada Apr 17 at 7:23
  • 1
    It should be like this Pattern.compile("[?.\\s]+").splitAsStream(message.toLowerCase()) .filter(w -> w.length() > 2).count() – Hadi J Apr 17 at 7:30

2 Answers 2

active oldest votes
up vote 2 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.599494 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO