Guest User

Untitled

a guest
Jun 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. public static void main(String[] args)
  2. {
  3. while (true)
  4. {
  5. System.out.println("Enter a sentence:");
  6. Scanner keyboard = new Scanner(System.in);
  7. String sentence = keyboard.nextLine();
  8.  
  9. if (sentence.isEmpty()) // quit the program when user enter an empty string
  10. {
  11. break;
  12. }
  13. else
  14. {
  15. StringTokenizer st = new StringTokenizer(sentence);
  16.  
  17. List<String> sentenceElement = new ArrayList<String>();
  18.  
  19. while (st.hasMoreTokens())
  20. {
  21. sentenceElement.add(st.nextToken());
  22. }
  23.  
  24. System.out.println(sentenceElement);
  25. }
  26. }
  27.  
  28. public static void main(String[] args){
  29. Scanner keyboard = new Scanner(System.in);
  30. String[] myPhrase = keyboard.nextLine().split(" ");
  31. HashMap<String, Integer> myWordsCount = new HashMap<String, Integer>();
  32. for (String s : myPhrase){
  33. if (myWordsCount.containsKey(s)) myWordsCount.replace(s, myWordsCount.get(s) + 1);
  34. else myWordsCount.put(s, 1);
  35. }
  36. System.out.println(myWordsCount);
  37. }
  38.  
  39. One two three four and again three and four
  40. {four=2, and=2, One=1, again=1, two=1, three=2}
  41.  
  42. import java.util.Arrays;
  43. import java.util.stream.Collectors;
  44.  
  45. public class StringFrequencyMap {
  46. public static void main(String... args) {
  47. String[] wordArray = {"Apple", "is", "an", "apple", "is", "a", "phone"};
  48. var freqCaseSensitive = Arrays.stream(wordArray)
  49. .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
  50. //If you want case insensitive then use
  51. var freqCaseInSensitive = Arrays.stream(wordArray)
  52. .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
  53.  
  54. System.out.println(freqCaseSensitive);
  55. System.out.println(freqCaseInSensitive);
  56. }
  57. }
  58.  
  59. {a=1, apple=1, Apple=1, phone=1, is=2, an=1}
  60. {a=1, apple=2, phone=1, is=2, an=1}
Add Comment
Please, Sign In to add comment