我从MasterList
表查询获取以下记录:迭代和比较Java列表
id listName listValue
1 Type of Repository Animal Specimen
2 Type of Repository Human Specimen
3 Type of Repository Environmental Specimen
4 Type of Repository Microorganism Culture Collection
5 Type of Repository Vegetal Specimen
6 Type of Repository Other
每个记录/行是一个对象,并存储为对象的列表下面的列表
List<MasterList> typeOfRepositoryMasterList
同样,每个对象都有对应的getter
方法可用列,如obj.getListValue();
然后从其他查询到biobankList
表我有如下记录:
biobankId listName listValue
1 Type of Repository Animal Specimen
1 Type of Repository Human Specimen
1 Type of Repository Microorganism Culture Collection
1 Type of Repository Vegetal Specimen
同样这些记录也可以作为对象的列表作为
List<biobankList> typeOfRepositoryBiobankList
每个对象在这里也有相应的getter
方法。
我想要做的是,对于第一个记录集中的所有listValue
,如果在第二个记录集中有相同的listValue
,则将其添加到新列表中,如selectedList
。在第二个记录集中不存在的两个listValue
应该被添加到availableList
。图片可能更好地解释。
for(MasterList attributeMaster: typeOfRepositoryMasterList){
boolean selected = false;
for(biobankList attribute: typeOfRepositoryBiobankList){
if(attributeMaster.getListValue().equals(attribute.getListValue())){
System.out.println("equal");
selected = true;
selectedList.add(new KeyValuePair(
attribute.getListName()+"_"+attribute.getListValue(), attribute.getListValue()));
break;
}
if(!selected){
System.out.println("not equal");
availableList.add(new KeyValuePair(
attributeMaster.getListName()+"_"+attributeMaster.getListValue(), attributeMaster.getListValue()));
}
}
}
的查询工作正常,但这种嵌套的for循环代码显然是不能工作,因为它增加了相同的值多次。
编辑:我试着添加boolean
但仍然存在问题。我在selectedList中获得了正确的值,但显然availableList包含重复的值。这是截图。
添加列表。包含(对象o)你的if – user3487063 2014-08-29 13:38:47
我也试过,但它仍然不起作用,因为我在availableList中获得重复的值。 – SASM 2014-08-29 13:44:52
看看我的答案我认为你有问题与availableList不是吗? – 2014-08-29 13:50:04