I have two array lists of objects, I need to compare them by the property value and to return unique. Object has two properties, question and answer, only the objects from list one with unique question should be returned.
*faq(question, answer)*
List<faq> one = new ArrayList<>();
one.add(new faq("question 1", "answer 1"));
one.add(new faq("question 2", "answer 2"));
one.add(new faq("question 3", "answer 3"));
List<faq> two = new ArrayList<>();
two.add(new faq("question 4", "answer 4"));
two.add(new faq("question 5", "answer 5"));
two.add(new faq("question 1", "answer 6"));
two.add(new faq("question 7", "answer 7"));
two.add(new faq("question 8", "answer 8"));
From this code here I want to get objects from list one with questions 2 and 3 since only those two are not contained in list two
You need to implement the equals()
and hashCode()
in Faq.java
import java.util.Objects;
import java.util.StringJoiner;
public class Faq {
private String questions;
private String answer;
public Faq(final String questions, final String answer) {
this.questions = questions;
this.answer = answer;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Faq faq = (Faq) o;
return questions.equals(faq.questions);
}
@Override
public int hashCode() {
return Objects.hash(questions);
}
@Override
public String toString() {
return new StringJoiner(", ", Faq.class.getSimpleName() + "[", "]")
.add("questions='" + questions + "'")
.toString();
}
}
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Faq> one = new ArrayList<>();
one.add(new Faq("question 1", "answer 1"));
one.add(new Faq("question 2", "answer 2"));
one.add(new Faq("question 3", "answer 3"));
List<Faq> two = new ArrayList<>();
two.add(new Faq("question 4", "answer 4"));
two.add(new Faq("question 5", "answer 5"));
two.add(new Faq("question 1", "answer 6"));
two.add(new Faq("question 7", "answer 7"));
two.add(new Faq("question 8", "answer 8"));
one.removeAll(two);
System.out.println(one);
}
}
[Faq[questions='question 2'], Faq[questions='question 3']]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments