Finding repeated words on a string and counting the repetitions

后端 未结 29 1225
梦谈多话
梦谈多话 2021-02-05 17:49

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         


        
29条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 18:27

    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]
    

提交回复
热议问题