Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args)
- {
- while (true)
- {
- System.out.println("Enter a sentence:");
- Scanner keyboard = new Scanner(System.in);
- String sentence = keyboard.nextLine();
- if (sentence.isEmpty()) // quit the program when user enter an empty string
- {
- break;
- }
- else
- {
- StringTokenizer st = new StringTokenizer(sentence);
- List<String> sentenceElement = new ArrayList<String>();
- while (st.hasMoreTokens())
- {
- sentenceElement.add(st.nextToken());
- }
- System.out.println(sentenceElement);
- }
- }
- public static void main(String[] args){
- Scanner keyboard = new Scanner(System.in);
- String[] myPhrase = keyboard.nextLine().split(" ");
- HashMap<String, Integer> myWordsCount = new HashMap<String, Integer>();
- for (String s : myPhrase){
- if (myWordsCount.containsKey(s)) myWordsCount.replace(s, myWordsCount.get(s) + 1);
- else myWordsCount.put(s, 1);
- }
- System.out.println(myWordsCount);
- }
- One two three four and again three and four
- {four=2, and=2, One=1, again=1, two=1, three=2}
- import java.util.Arrays;
- import java.util.stream.Collectors;
- public class StringFrequencyMap {
- public static void main(String... args) {
- String[] wordArray = {"Apple", "is", "an", "apple", "is", "a", "phone"};
- var freqCaseSensitive = Arrays.stream(wordArray)
- .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
- //If you want case insensitive then use
- var freqCaseInSensitive = Arrays.stream(wordArray)
- .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
- System.out.println(freqCaseSensitive);
- System.out.println(freqCaseInSensitive);
- }
- }
- {a=1, apple=1, Apple=1, phone=1, is=2, an=1}
- {a=1, apple=2, phone=1, is=2, an=1}
Add Comment
Please, Sign In to add comment