के साथ शब्द गणना मैं जावा 8 में एक शब्द गणना कार्यक्रम को लागू करने की कोशिश कर रहा हूं लेकिन मैं इसे काम करने में असमर्थ हूं। विधि को पैरामीटर के रूप में एक स्ट्रिंग लेनी चाहिए और Map<String,Integer>
देता है।जावा 8
जब मैं इसे पुराने जावा तरीके से कर रहा हूं, तो कुछ भी ठीक काम करता है। लेकिन जब मैं जावा 8 में ऐसा करने की कोशिश कर रहा हूं, तो यह एक नक्शा देता है जहां कुंजी सही घटनाओं के साथ खाली होती है।
public Map<String, Integer> count(String input){
Map<String, Integer> wordcount = new HashMap<>();
Pattern compile = Pattern.compile("(\\w+)");
Matcher matcher = compile.matcher(input);
while(matcher.find()){
String word = matcher.group().toLowerCase();
if(wordcount.containsKey(word)){
Integer count = wordcount.get(word);
wordcount.put(word, ++count);
} else {
wordcount.put(word.toLowerCase(), 1);
}
}
return wordcount;
}
मुख्य कार्यक्रम:
public static void main(String[] args) {
WordCount wordCount = new WordCount();
Map<String, Integer> phrase = wordCount.countJava8("one fish two fish red fish blue fish");
Map<String, Integer> count = wordCount.count("one fish two fish red fish blue fish");
System.out.println(phrase);
System.out.println();
System.out.println(count);
}
public Map<String, Integer> countJava8(String input){
return Pattern.compile("(\\w+)").splitAsStream(input).collect(Collectors.groupingBy(e -> e.toLowerCase(), Collectors.reducing(0, e -> 1, Integer::sum)));
}
यहाँ कोड मैं एक सामान्य स्थिति में प्रयोग करेंगे है:
यहाँ एक जावा 8 शैली में मेरी कोड है
जब मैं इस प्रोग्राम को चलाता हूं, मेरे पास आउटपुट है:
{ =7, =1}
{red=1, blue=1, one=1, fish=4, two=1}
मैंने सोचा कि विधि splitAsStream
Stream
के रूप में regex में मिलान तत्वों को स्ट्रीम करेगा। मैं इसे कैसे ठीक कर सकता हूं?
@ बम्बल-मधुमक्खी-टूना संपादन को प्रश्न के महत्वपूर्ण हिस्सों को नहीं हटाया जाना चाहिए या स्वरूपण से परे कोड संशोधित नहीं करना चाहिए।आपने दिए गए उदाहरण को बदल दिया और अंतिम प्रश्न के अलावा उस उदाहरण के लिए आउटपुट को हटा दिया। मैंने प्रश्न को मूल संशोधन में वापस ले लिया है। – Vulcan
'wordCount.Phrase() 'क्या है? –
समस्या यह है कि आप '\ w' द्वारा 'विभाजित' करते हैं, इसलिए आप मूल रूप से सबकुछ प्राप्त करते हैं जो _not_ शब्द है। –