[英]How to Compare two lists in java
我有两个列表List listOne,List listTwo,并且我想比较两个列表,如果两者相同,则要将列表项添加到其他列表ol1中,否则添加到ol2中。
这里,ElementRangeIndex是一个包含一些字符串值的bean类。
比较两个列表时,需要比较Bean中的每个字符串值。
我已经使用了以下代码,但是由于两个列表具有不同的对象,因此包含添加重复的值。
public static Map<Integer, List<ElementRangeIndex>> compareLists(List<ElementRangeIndex> listOne, List<ElementRangeIndex> listTwo) {
boolean indicator = false;
List<ElementRangeIndex> listOnes = new ArrayList<ElementRangeIndex>();
List<ElementRangeIndex> listTwos = new ArrayList<ElementRangeIndex>();
List<ElementRangeIndex> listThree = new ArrayList<ElementRangeIndex>();
Map<Integer, List<ElementRangeIndex>> map = new HashMap<Integer, List<ElementRangeIndex>>();
if (listOne!= null && listTwo!=null && listOne.size() == listTwo.size()) {
for (ElementRangeIndex listTwoData : listTwo) {
for (ElementRangeIndex listOneData : listOne) {
/* if (listOneData.getNamespaceUri().equals(listTwoData.getNamespaceUri())
&& listOneData.getCollation().equals(listTwoData.getCollation())
&& listOneData.getScalarType().equals(listTwoData.getScalarType())
&& listOneData.getLocalname().equals(listTwoData.getLocalname())) {*/
if ((listOneData.getNamespaceUri().hashCode()== listTwoData.getNamespaceUri().hashCode())
&& (listOneData.getCollation().hashCode() == listTwoData.getCollation().hashCode())
&& (listOneData.getScalarType().hashCode() == listTwoData.getScalarType().hashCode())
&& (listOneData.getLocalname().hashCode() == listTwoData.getLocalname().hashCode())) {
listOnes.add(listOneData);
if(listTwos.contains(listOneData))
listTwos.remove(listOneData);
if(listTwos.contains(listTwoData))
listTwos.remove(listTwoData);
if(listThree.contains(listOneData))
listThree.remove(listOneData);
if(listThree.contains(listTwoData))
listThree.remove(listTwoData);
}else{
if(!listOnes.contains(listOneData))
if(!listTwos.contains(listOneData))
listTwos.add(listOneData);
if(!listOnes.contains(listTwoData))
if(!listThree.contains(listTwoData))
listThree.add(listTwoData);
}
}
}
map.put(1,listOnes);
map.put(2, listTwos);
map.put(3, listThree);
}
return map;
}
我的目标是将类似的列表项添加到一个列表(listOnes)中,仅保留到其他列表(listTwos),而保留到其他列表(listThree)。
谢谢阿俊
如果您需要自己进行拆分,我可能会执行以下操作:
创建列表的副本并将其命名为leftOnly
。 这将仅包含列表一中的元素。
创建列表2的副本,并命名为rightOnly
。 这将仅包含列表二中的元素。
创建一个空列表intersectList
,其中将包含两个列表中都存在的元素。
到目前为止, leftOnly
可能包含太多元素,因此我们需要对其进行过滤。 为此,我们使用迭代器迭代每个元素,并检查它是否也包含在rightOnly
中。 如果是,我们从leftOnly
和rightOnly
删除该元素,并将其添加到intersectList
。
为了加快该过程(在列表中contains
和remove
列表是线性操作),可以将leftOnly
和rightOny
的类型设置为LinkedHashSet
,该类型允许更快的操作,但不允许重复(结果中使用重复会破坏整个逻辑)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.