我有两个列表 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
。这将包含仅出现在列表一中的元素。创建列表二的副本并命名为
rightOnly
。这将包含仅出现在列表二中的元素。创建一个空列表
intersectList
,其中将包含两个列表中都存在的元素。到目前为止,
leftOnly
可能包含太多元素,因此我们需要过滤这些元素。为此,我们使用迭代器迭代每个元素并检查它是否也包含在rightOnly
中。如果是,我们从leftOnly
和rightOnly
中删除该元素,并将其添加到intersectList
中。
为了加快该过程(列表上的 contains
和 remove
是线性操作),您可以将 leftOnly
和 rightOny
设为 LinkedHashSet
类型,这样可以加快操作速度,但不允许重复(在结果中使用重复项无论如何都会破坏整个逻辑)。
关于java - 如何在java中比较两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35062606/