osimer pothe
osimer pothe

Reputation: 2897

Code to determine no of different items in two arraylist

I have two arraylist which is defined as follows .

ArrayList<String> list1 = new arrayList<String>();
ArrayList<String> list2 = new arrayList<String>();

list1.add("sultan");
list1.add("Masum");
list1.add("sultan");
list1.add("Sorry");
list1.add("sultan");
list1.add("Masum");
list1.add("sultan");
list1.add("Tarek");
list1.add("sultan");

list2.add("Billal");
list2.add("Masum");
list2.add("Sorry");
list2.add("Sorry");
list2.add("sultan");
list2.add("Masum");
list2.add("Tanha");
list2.add("Tarek");
list2.add("Die");

I want to know the no of different items of the above two arraylist . For this I ahve the following piece of code .

int count=0;
for(String s1:list1)
{
    if(!list2.contains(s1)) 
        ++count;
}

for(String s2:list2)
{
    if(!list1.contains(s2)) 
        ++count;
}

But my code is very in-efficient . Can you please suggest me a better way to achieve my purpose ?

Upvotes: 2

Views: 124

Answers (3)

yamilmedina
yamilmedina

Reputation: 3395

You could use CollectionUtils.disjunction (from Apache Commons Lib), and then do a size() on the returning Collection.

    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();

    list1.add("sultan");
    list1.add("Masum");
    list1.add("sultan");
    list1.add("Sorry");
    list1.add("sultan");
    list1.add("Masum");
    list1.add("sultan");
    list1.add("Tarek");
    list1.add("sultan");

    list2.add("Billal");
    list2.add("Masum");
    list2.add("Sorry");
    list2.add("Sorry");
    list2.add("sultan");
    list2.add("Masum");
    list2.add("Tanha");
    list2.add("Tarek");
    list2.add("Die");

    int numOfDiffs = CollectionUtils.disjunction(list1, list2).size();
    System.out.println("Diffs: " + numOfDiffs);

Upvotes: 3

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

At first you can init your lists as following:

List<String> list1 = new ArrayList<>(Arrays.asList(new String[]{"sultan", "Masum", "others..."}));

And then you can calculate how much common elements they have, and remove this number from total:

int list1 oldSize = list1.size();
list1.retainAll(list2); // In list1 you get common elements

and

count = oldSize - list1.size();

If you don't want to change your arrays, you can copy them as following:

Collections.copy(newArray, oldArray); 

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213411

Instead of List you should use Set. Then what you're looking for is Symmetric Difference. If allowed, you can use Guava's Sets.symmetricDifference(Set, Set)

Upvotes: 3

Related Questions