Count the occurrences of elements in an ArrayList

I have an object java.util.ArrayList<Item>and Item.

Now I want to get the number of times it Itemis stored in an arraylist.

I know that I can perform a check arrayList.contains(), but it returns true, regardless of whether it contains one or more Items.

Q1. How can I find the amount of time an item is stored in a list?

Q2. In addition, if the list contains more than one element, then how can I determine the index of other elements, because arrayList.indexOf(item)each time it returns the index of only the first element?

+5
source share
6 answers

Collections:

public static int frequency(Collection<?> c, Object o)

, . e , (o == null? E == null: o.equals(e)).

, HashMap . - .. , , .

HashMap<Item, Integer> counters = new HashMap<Item, Integer>(5000);
ArrayList<Item> items = new ArrayList<Item>(5000);

void insert(Item newEl)
{
   if (counters.contains(newEl))
     counters.put(newEl, counters.get(newEl)+1);
   else
     counters.put(newEl, 1);

   items.add(newEl);
 }

: (, Apache Collections) Bag,

, , .

, .

+22

.

public int countNumberEqual(ArrayList<Item> itemList, Item itemToCheck) {
    int count = 0;
    for (Item i : itemList) {
        if (i.equals(itemToCheck)) {
          count++;
        }
    }
    return count;
}

, equals Item, ( Object.equals()).

. (, ), .

public List<Integer> indices(ArrayList<Item> items, Item itemToCheck) {
    ArrayList<Integer> ret = new ArrayList<Integer>();
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).equals(itemToCheck)) {
            ret.add(i);
        }
    }
    return ret;
}
+5

, ArrayList, O (n), n - . , SO, , !

, , , . , O (log n) , ; hashcode, equals, .

- . HashMap, , . , , o (1).

0

, , , , Multiset ( google-collections/guava), List. , Set, . , int count(Object element), , . , HashMap, .

0

. , - , .

void insert(Item newEl) 
{ 
   if (counters.contains(newEl)) 
     counters.put(newEl, counters.get(newEl)+1); 
   else 
     counters.put(newEl, 1); 

   items.add(newEl); 
 } 

. .

,

http://binodsuman.blogspot.com

0
source

I know this is an old post, but since I did not see a solution with a hash map, I decided to add pseudocode to the hash map for everyone who would need it in the future. Assuming arraylist and float data types.

 Map<Float,Float> hm = new HashMap<>();
 for(float k : Arralistentry) {
 Float j = hm.get(k);
 hm.put(k,(j==null ? 1 : j+1));
 }
 for(Map.Entry<Float, Float> value : hm.entrySet()) {
System.out.println("\n" +value.getKey()+" occurs : "+value.getValue()+" times");
  }
0
source

All Articles