I am trying to optimize a piece of code which compares elements of list.
Eg.
public void compare(Set<Record> firstSet, Set<Record> secondSet){
for(Record firstRecord : firstSet){
for(Record secondRecord : secondSet){
// comparing logic
}
}
}
Please take into account that the number of records in sets will be high.
Thanks
Shekhar
There is a method in Guava
Sets
which can help here:If you are using
Guava
library it's possible to do:And then make a conclusion based on these.
I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,
It really depends on what you want to do in the comparison logic... ie what happens if you find an element in one set not in the other? Your method has a
void
return type so I assume you'll do the necessary work in this method.More fine-grained control if you need it:
If you need to get the elements that are in one set and not the other.
EDIT:
set.removeAll(otherSet)
returns a boolean, not a set. To use removeAll(), you'll have to copy the set then use it.If the contents of
one
andtwo
are both empty, then you know that the two sets were equal. If not, then you've got the elements that made the sets unequal.You mentioned that the number of records might be high. If the underlying implementation is a
HashSet
then the fetching of each record is done inO(1)
time, so you can't really get much better than that.TreeSet
isO(log n)
.I would put the secondSet in a HashMap before the comparison. This way you will reduce the second list's search time to n(1). Like this:
You have the following solution from https://www.mkyong.com/java/java-how-to-compare-two-sets/
Or if you prefer to use a single return statement: