I have an object java.util.ArrayList<Item>and Item.
java.util.ArrayList<Item>
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.
arrayList.contains()
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?
arrayList.indexOf(item)
Collections:
Collections
public static int frequency(Collection<?> c, Object o)
, . e , (o == null? E == null: o.equals(e)).
, HashMap . - .. , , .
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,
Bag
, , .
, .
.
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()).
equals
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; }
, ArrayList, O (n), n - . , SO, , !
, , , . , O (log n) , ; hashcode, equals, .
hashcode
- . HashMap, , . , , o (1).
, , , , Multiset ( google-collections/guava), List. , Set, . , int count(Object element), , . , HashMap, .
List
Set
int count(Object element)
. , - , .
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
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"); }