How to Count Repetition of Words in Array List?

后端 未结 5 880
醉话见心
醉话见心 2020-12-22 08:04

I\'ve these code for searching occurrence in Array-List but my problem is how I can get result out side of this for loop in integer type cause I need in out side , may be th

5条回答
  •  粉色の甜心
    2020-12-22 08:42

    Set unique = new HashSet(list);

    and

    Collections.frequency(list, key);

    are too much overhead.

    Here is how i would do it

    List list = new ArrayList();
    list.add("aaa");
    list.add("bbb");
    list.add("aaa");
    
    Map countMap = new HashMap<>();
    
    
    for (String word : list) {
        Integer count = countMap.get(word);
        if(count == null) {
            count = 0;
        }
        countMap.put(word, (count.intValue()+1));
    }
    
    System.out.println(countMap.toString());
    

    Output

    {aaa=2, bbb=1}
    

    EDIT output one by one: iterate over the set of entries of the map

    for(Entry entry : countMap.entrySet()) {
        System.out.println("frequency of '" + entry.getKey() + "' is "
              + entry.getValue());
    }
    

    Output

    frequency of 'aaa' is 2
    frequency of 'bbb' is 1
    

    EDIT 2 No need for looping

    String word = null;
    Integer frequency = null;
    
    word = "aaa";
    frequency = countMap.get(word);
    System.out.println("frequency of '" + word + "' is " +
        (frequency == null ? 0 : frequency.intValue()));
    
    word = "bbb";
    frequency = countMap.get(word);
    System.out.println("frequency of '" + word + "' is " + 
        (frequency == null ? 0 : frequency.intValue()));
    
    word = "foo";
    frequency = countMap.get(word);
    System.out.println("frequency of '" + word + "' is " + 
        (frequency == null ? 0 : frequency.intValue()));
    

    Output

    frequency of 'aaa' is 2
    frequency of 'bbb' is 1
    frequency of 'foo' is 0
    

    Note that you will always have a collection and you need extract the count from it for a particular word one way or another.

提交回复
热议问题