How to count the number of occurrences of an element in a List

后端 未结 22 1503
一生所求
一生所求 2020-11-22 12:25

I have an ArrayList, a Collection class of Java, as follows:

ArrayList animals = new ArrayList();
animals.add(\"bat\         


        
22条回答
  •  没有蜡笔的小新
    2020-11-22 12:47

    I didn't want to make this case more difficult and made it with two iterators I have a HashMap with LastName -> FirstName. And my method should delete items with dulicate FirstName.

    public static void removeTheFirstNameDuplicates(HashMap map)
    {
    
        Iterator> iter = map.entrySet().iterator();
        Iterator> iter2 = map.entrySet().iterator();
        while(iter.hasNext())
        {
            Map.Entry pair = iter.next();
            String name = pair.getValue();
            int i = 0;
    
            while(iter2.hasNext())
            {
    
                Map.Entry nextPair = iter2.next();
                if (nextPair.getValue().equals(name))
                    i++;
            }
    
            if (i > 1)
                iter.remove();
    
        }
    
    }
    

提交回复
热议问题