I have two arraylists of objects, I want to know which strings are unique to arraylist 1, and which strings are unique to arraylist 2. What I have come up with is the forloop below, which I have to implement twice, reversing the positions of the arraylists. I'm hopeful someone can suggest a more elegant way to do this.
Per request, a bunch more stuff I guess I wrongfully assumed was implied in the code-snippet itself. And the output this produces is:
grape doesn't exist in second arrayList
pineapple doesn't exist in first arrayList
Works great, everything is great, but, per above, I'm hopeful someone with more knowledge of streams/java in general can provide a better solution than just running my stream twice, with the inputs reversed.
import java.util.ArrayList;
public class CompareTwoArrays {
ArrayList<MyCustomObject> firstArrayListOfObjects = new ArrayList<>();
ArrayList<MyCustomObject> secondArrayListOfObjects = new ArrayList<>();
public void superSpecificExampleMethod() {
firstArrayListOfObjects.add(new MyCustomObject(1, 1, "apple"));
firstArrayListOfObjects.add(new MyCustomObject(1, 1, "orange"));
firstArrayListOfObjects.add(new MyCustomObject(1, 1, "banana"));
firstArrayListOfObjects.add(new MyCustomObject(1, 1, "grape"));
secondArrayListOfObjects.add(new MyCustomObject(1, 1, "apple"));
secondArrayListOfObjects.add(new MyCustomObject(1, 1, "pineapple"));
secondArrayListOfObjects.add(new MyCustomObject(1, 1, "orange"));
secondArrayListOfObjects.add(new MyCustomObject(1, 1, "banana"));
for (MyCustomObject object : firstArrayListOfObjects) {
if (!secondArrayListOfObjects.stream().map(MyCustomObject::getString).filter(object.getString()::equals).findFirst().isPresent()) {
System.out.println(object.getString() + " doesn't exist in second arrayList");
}
}
for (MyCustomObject object : secondArrayListOfObjects) {
if (!firstArrayListOfObjects.stream().map(MyCustomObject::getString).filter(object.getString()::equals).findFirst().isPresent()) {
System.out.println(object.getString() + " doesn't exist in first arrayList");
}
}
}
}
class MyCustomObject {
private int randomIntOne;
private int randomIntTwo;
private String string;
public MyCustomObject(int randomIntOne, int randomIntTwo, String string) {
this.randomIntOne = randomIntOne;
this.randomIntTwo = randomIntTwo;
this.string = string;
}
public String getString() {
return string;
}
}
Objectclass does not have methodgetString. Do you mean you have your own POJO with this method?