ChatGPT solving famous word count problem

ChatGPT solving famous word count problem

My question to ChatGPT - Write a Java lambda for me, which reads a sentence given as a String and produces a Map which counts the occurrences of each word in the given String

Response: Sure, here's a Java lambda that takes in a sentence as a String and returns a Map containing the word count:

import java.util.Arrays
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


public class WordCountLambda {

? ? public static void main(String[] args) {
? ? ? ? String sentence = "This is a sample sentence for testing" + 
              " the word count lambda function";
? ? ? ? Map<String, Long> wordCount = Arrays.stream(
                sentence.toLowerCase().split("\\s+"))
? ? ? ? ? ? ? ? .collect(Collectors.groupingBy(Function.identity(), 
                   Collectors.counting()));
? ? ? ? System.out.println(wordCount);
? ? }
}        

In the lambda, the sentence String is first converted to lowercase using `toLowerCase()`, and then split into words using split("\\s+"), which splits on any whitespace character. The resulting array of words is then converted to a stream using Arrays.stream().

Using the Collectors.groupingBy() method, the stream is then grouped by each word's identity using Function.identity(), and the number of occurrences of each word is counted using Collectors.counting(). The resulting Map<String, Long> contains each word as a key, and the number of occurrences of each word as a value.

Finally, the resulting map is printed to the console using System.out.println(wordCount).

要查看或添加评论,请登录

Arpan Das的更多文章

社区洞察

其他会员也浏览了