I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:
String s = \"House, House
Using java8
private static void findWords(String s, List output, List count){
String[] words = s.split(", ");
Map map = new LinkedHashMap<>();
Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
map.forEach((k,v)->{
output.add(k);
count.add(v);
});
}
Also, use a LinkedHashMap if you want to preserve the order of insertion
private static void findWords(){
String s = "House, House, House, Dog, Dog, Dog, Dog";
List output = new ArrayList<>();
List count = new ArrayList<>();
findWords(s, output, count);
System.out.println(output);
System.out.println(count);
}
Output
[House, Dog]
[3, 4]