我有两个列表
类文章
public class Article{
int id;
String name;
// get
// set
}
列表一:
List<Article> mListInfor have
id = 1, 2 , 3, 4, 5
name = "A", "B", "C", "D", "E"
列表二:
List<Article> mListNews have
id = 1, 2, 3, 4, 5, 6, 7, 8
name = "A", "B", "C", "D", "E", "F", "G", "H"
结果:
List<Article> mListDiffrent have
id = 6,7,8
name = "F","G","H"
如何从这两个数组列表中获取不同的值:List mListInfor 和 List mListNews ?
请。帮助我!
最佳答案
您应该重写类中的Equals
方法,然后使用一些内置方法。例如
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)
编辑
根据您调用removeAll的顺序,结果可能会受到影响。然而,apache commons (CollectionUtils
) 中有一个已经构建的功能,这将使您不必担心这一点。
CollectionUtils.intersection(mListInfor, mListNews);
关于java - 如何从 Java/Android 中的两个 ArrayList 获取不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979060/