Skip to content

Instantly share code, notes, and snippets.

@gaborantal
Last active April 25, 2019 16:37
Show Gist options
  • Save gaborantal/9eba6a8097b7050eb2fca78b96ef5f22 to your computer and use it in GitHub Desktop.
Save gaborantal/9eba6a8097b7050eb2fca78b96ef5f22 to your computer and use it in GitHub Desktop.
Compare two list of objects without using equals
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
class ClassCannotBeModified {
public int a;
public int b;
public ClassCannotBeModified(int a, int b) {
this.a = a;
this.b = b;
}
}
public class CompareLists {
public static final <T> boolean compareListsWithoutEquals(List<T> first, List<T> second, BiFunction<T, T, Boolean> eq) {
if (first == second) {
return true;
}
if ((first == null && second != null) || (first != null && second == null)) {
return false;
}
if (first.size() != second.size()) {
return false;
}
int neededTrues = first.size();
int trues = 0;
for (T f : first) {
for (T s : second) {
if (eq.apply(f, s)) {
trues++;
}
}
}
return neededTrues == trues;
}
public static void main(String[] args) {
List<ClassCannotBeModified> first = new ArrayList<>();
first.add(new ClassCannotBeModified(2, 1));
first.add(new ClassCannotBeModified(5, 4));
first.add(new ClassCannotBeModified(7, 9));
List<ClassCannotBeModified> second = new ArrayList<>();
second.add(new ClassCannotBeModified(2, 1));
second.add(new ClassCannotBeModified(5, 4));
second.add(new ClassCannotBeModified(7, 9));
boolean listsAreEqual = compareListsWithoutEquals(first, second, (e1, e2) -> {
return e1.a == e2.a && e1.b == e2.b;
});
System.out.println(listsAreEqual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment