Ramkumar P
Ramkumar P

Reputation: 209

How to find the difference between two arraylist without changing the first arraylist value in Java?

I have two arraylists named fw_week and sw_week... Now have to calculate fw_diff which is difference between fw_week and sw_week and sw_diff which is difference between sw_week and fw_week...

I have used like following script,

    fw_diff=fw_week;
    sw_diff=sw_week;
    fw_diff.removeAll(sw_week);
    sw_diff.removeAll(fw_week);

In this, am getting the fw_diff correctly but the fw_week value is also changed which now equal to fw_diff, so the second value sw_diff is giving the wrong value, but i don't want to change the fw_week and sw_week values... So please can anyone help me to solve this issue....

Upvotes: 3

Views: 1681

Answers (3)

Priyank Doshi
Priyank Doshi

Reputation: 13151

fw_diff= fw_week.clone().removeAll(sw_week)
sw_diff=sw_week.clone().removeAll(fw_week)

More efficient one:

fw_diff= fw_week.clone().removeAll(sw_week)
sw_diff=sw_week.clone().removeAll(fw_diff)

Here,fw_diff contains intersaction of both the list. So now , for sw_diff , we need to remove only fw_diff from sw_week . No need to remove all of fw_week .

Upvotes: 3

Jon Lin
Jon Lin

Reputation: 143886

You need to clone the arrays:

fw_diff=fw_week.clone();
sw_diff=sw_week.clone();

before you do any removing.

Upvotes: 0

AngelsandDemons
AngelsandDemons

Reputation: 2843

We do the same thing in our application like this:-

Our scenario is we have 2 arraylist and I need to find the difference between first and second arraylist.

Following is the code snippet:-

this.lstDifference=(ArrayList<String>) ListUtils.subtract(FirstArrayList,SecondArrayList);

The type of arraylist can be changed depending upon your two arraylists.

Upvotes: 0

Related Questions