You need to find the intersection of both lists. In detail: The number of elements of the first list that are also contained in the second list:
List<Point> first = ...;
List<Point> second = ...;
int count = 0;
for (Point p : first) {
if (second.contains(p)) count++;
}
// assuming, first and second have equal size
double percentage = (double)count / first.size();
Containment operations are much more efficient in a Set
than a List
, so if you have a lot of elements, it might be considerably faster, to use a Set
for second
:
Set<Point> second = new HashSet<Point>(secondList);
Fortunately, a Set
already offers a method to perform an intersection operation: Set.retainAll(Collection other)
. Java API Docs:
Retains only the elements in this set that are contained in the
specified collection (optional operation).
So to get the intersection of two collections, we can simply use this method:
Collection<Point> first = ...; // should be a Set for maximum performance
Set<Point> second = new HashSet<Point>(...);
second.retainAll(first);
// assuming, both point lists have equal size
double percentage = (double)count / first.size();
Note: All this code only works if class Point
has correctly overwritten equals
and hashcode
. See https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.