[英]How to get different values from two ArrayList in Java/Android?
I have two List 我有两个清单
Class Article 课堂文章
public class Article{
int id;
String name;
// get
// set
}
List one: 清单一:
List<Article> mListInfor have
id = 1, 2 , 3, 4, 5
name = "A", "B", "C", "D", "E"
List Two: 清单二:
List<Article> mListNews have
id = 1, 2, 3, 4, 5, 6, 7, 8
name = "A", "B", "C", "D", "E", "F", "G", "H"
Result: 结果:
List<Article> mListDiffrent have
id = 6,7,8
name = "F","G","H"
How can I get different value from these two arraylists: List mListInfor and List mListNews ? 如何从这两个数组列表(List mListInfor和List mListNews)中获得不同的值?
Please. 请。 Help me!
帮我!
You should override the Equals
method in your class, and then use some built-in methods. 您应该在类中重写
Equals
方法,然后使用一些内置方法。 For example 例如
public class Article{
int id;
String name;
// get
// set
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Article))
return false;
if (obj == this)
return true;
return this.id == obj.id;
}
}
List<Article> differences = new ArrayList<>();
differences.addAll(mListInfor)
differences.removeAll(mListNews)
Depending on the order of your call to removeAll, the result can be affected. 根据对removeAll的调用顺序,结果可能会受到影响。 However, there is a already-built feature in apache commons (
CollectionUtils
) which will make you not worry about that. 但是,apache commons(
CollectionUtils
)中已经有一个内置的功能,这使您不必担心。
CollectionUtils.intersection(mListInfor, mListNews);
Solution given by @rafael in above answer is good solution where you are using inbuilt feature. @rafael在上面的答案中给出的解决方案是使用内置功能的好解决方案。
You can also create a function where you can individually traverse each element of article lost and segregate by using comparator implementation or even equals comparison is good. 您还可以创建一个函数,在该函数中可以使用比较器实现逐个遍历文章丢失和隔离的每个元素,甚至可以说比较比较好。
Also don't forget to explore streams in Java 8. There must be good options in stream api. 另外,不要忘记在Java 8中探索流。流api中必须有不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.