How to Count Repetition of Words in Array List?

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

    I would sort the list first to avoid going thru the whole list with Collections.frequency every time. The code will be longer but much more efficient

        List list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("aaa");
        Map map = new HashMap();
        Collections.sort(list);
        String last = null;
        int n = 0;
        for (String w : list) {
            if (w.equals(last)) {
                n++;
            } else {
                if (last != null) {
                    map.put(last, n);
                }
                last = w;
                n = 1;
            }
        }
        map.put(last, n);
        System.out.println(map);
    

    output

    {aaa=2, bbb=1}
    

提交回复
热议问题