Sangram Anand
Sangram Anand

Reputation: 10650

Merging two Array List in Java

I have two Array list say currentTopicsDetailsList and updatedTopicsDetailsList. The Lists are of object Topic(class) i.e.,

List<Topic> currentTopicsDetailsList;
List<Topic> updatedTopicsDetailsList; 

The class Topic has properties

I want to update the values in currentTopicsDetailsList with updatedTopicsDetailsList values
e.g. at

I want to overwrite the currentTopicsDetailsList[4] with updatedTopicsDetailsList[4] with a condition that whichever has null should be ignore i.e., rank property should be 158 eventhough its null in updatedTopicsDetailsList[4].rank

Right now am doing it with FOR loop index level comparison for null & empty strings, but is there a alternative and quick way of doing things.

Upvotes: 1

Views: 3142

Answers (2)

Zaw Than oo
Zaw Than oo

Reputation: 9935

Just use Set/HashSet. Convert one of list to Set. And use addAll method.

Note Make sure override equals and hashcode method of Topic.

List<Topic> currentTopicsDetailsList;
List<Topic> updatedTopicsDetailsList; 
HashSet<Topic> set = new HashSet<Topic>(currentTopicsDetailsList);
set.addAll(updatedTopicsDetailsList);

updatedTopicsDetailsList = new ArrayList<Topic>(set);

Update Comment

 do i have to include all the fields for generating equals() & hascode() ?

Sorry, I am not sure, all fields for generating equals() & hascode() because of it is depend on your requirement.

For example :

Topic have a field name with id. As two Topic instances have same id, if we assume these two instance are same, you just need to put id into equals() & hascode(). The rest of fields don't need to put.

Upvotes: 3

vels4j
vels4j

Reputation: 11298

Simply put a method in Topic class to update

public void update(Topic updatedTopic){
   if(updatedTopic.getRank()!=null){
      this.rank = updatedTopic.getRank();
   }
   // similarly u can check others
}

and for merging to list you can do like

int size = currentTopicsDetailsList.size();
for(int i=0;i<size;i++) {
  Topic uT = updatedTopicsDetailsLIst.get(i);
  Topic cT = currentTopicsDetailsList.get(i);
  cT.update(uT); 
}

Make sure both list contain ordered same Topic

Upvotes: 3

Related Questions