Finding repeated words on a string and counting the repetitions

后端 未结 29 895
梦谈多话
梦谈多话 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:05

    as introduction of stream has changed the way we code; i would like to add some of the ways of doing this using it

        String[] strArray = str.split(" ");
        
        //1. All string value with their occurrences
        Map counterMap = 
                Arrays.stream(strArray).collect(Collectors.groupingBy(e->e, Collectors.counting()));
    
        //2. only duplicating Strings
        Map temp = counterMap.entrySet().stream().filter(map->map.getValue() > 1).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
        System.out.println("test : "+temp);
        
        //3. List of Duplicating Strings
        List masterStrings = Arrays.asList(strArray);
        Set duplicatingStrings = 
                masterStrings.stream().filter(i -> Collections.frequency(masterStrings, i) > 1).collect(Collectors.toSet());
    

提交回复
热议问题