I have two generic list of Data Type class:RequiredList & PrimaryList
public class Data{
private String dataCode;
private String dataDesc;
public String getDataCode(){}
public void setDataCode(String dataCode){}
public String getDataDesc(){}
public void setDataDesc(String dataDesc){}
}
public static void main(String[] args) {
List<Data> primaryList = new ArrayList<Data>();
for (int i = 2; i < 5; i++) {
Data data = new Data();
data.setDataCode("code" + i);
data.setDataDesc("desc" + i);
primaryList.add(data);
}
List<Data> requiredList = new ArrayList<Data>();
for (int i = 0; i < 8; i++) {
Data data = new Data();
data.setDataCode("code" + i);
data.setDataDesc("desc" + i);
requiredList.add(data);
}
StringBuffer partyList = new StringBuffer();
for (int i = 0; i < requiredList.size(); i++) {
if (primaryList.size() > i
&& !requiredList.get(i).getDataCode().equals(primaryList.get(i).getDataCode())) {
partyList.append(requiredList.get(i).getDataDesc());
partyList.append(",");
}
if(primaryList.size() <= i)
{
partyList.append(requiredList.get(i).getDataDesc());
partyList.append(",");
}
}
System.out.println(partyList.toString());
}
I want to compare elements of requiredList to elements of primaryList.Those elements of primaryList are not present in requiredList , they will be added in new list.Can anybody help me out?
First you need to implement equals()
and hashcode()
for Data
Then
List<Data> newlist = new ArrayList<Data>();
for(Data data : primaryList ) {
if(!requiredList.contains(data) ) {
newlist.add(data);
}
}
If you okay to modify primaryList then removeAll
would do the trick
primaryList.removeAll(requiredList);
As @Subin S pointed out equals
and hashCode
need to be overriden for Data
.
Those elements of primaryList are not present in requiredList , they will be added in new list.
Look at the List removeAll()
or retainAll()
methods are useful in your usecase.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.