How to Count Repetition of Words in Array List?

后端 未结 5 889
醉话见心
醉话见心 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:28

    The Map answers work, but you can extend this answer to solve more problems.

    You create a class that has the field values you need, and put the class in a List.

    import java.util.ArrayList;
    import java.util.List;
    
    public class WordCount {
    
        private String word;
        private int count;
    
        public WordCount(String word) {
            this.word = word;
            this.count = 0;
        }
    
        public void addCount() {
            this.count++;
        }
    
        public String getWord() {
            return word;
        }
    
        public int getCount() {
            return count;
        }
    
    }
    
    class AccumulateWords {
        List list    = new ArrayList();
    
        public void run() {
            list.add(new WordCount("aaa"));
            list.add(new WordCount("bbb"));
            list.add(new WordCount("ccc"));
    
            // Check for word occurrences here
    
            for (WordCount wordCount : list) {
                int accurNO = wordCount.getCount();
                System.out.println(wordCount.getWord() + ": " + accurNO);
            }
        }
    }
    

提交回复
热议问题