I would like to check if an Arraylist contains n copies of the same element. Here's the problem:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testMain {
public static void main(String[] args) {
myClass myObject = new myClass("haha1");
ArrayList a = new ArrayList();
a.add(myObject);
a.add(new myClass("haha2"));
a.add(new myClass("haha3"));
List b;
b = Collections.nCopies(5, myObject);
System.out.println(a.containsAll(b)); //prints true
}
static private class myClass {
String a;
myClass(String a) {
this.a = a;
}
}
}
Problem 1: List b
has a greater size than list a
- should be false
Problem 2: List b
has more than one myObject
objects (as opposed to Lista
- should be false
This doesn't work due to the way containsAll works, since I want to see if the object myObject
is contained (in this case) 3 times in List a
.
I know I can write my own method that would do exactly what I want, but I was wondering if there is an out of the box solution for this case or what would be the most "elegant" way of handling it.
EDIT: Removed clarification for my use of myClass
as it was conflicting with given example.
Use Collections.frequency(a,myObject) == 5
(or Collections.frequency(a,myObject) >= 5
if you don't mind if your Collection
has more than 5 instances pf myObject
).
int java.util.Collections.frequency(Collection c, Object o)
Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).