确定两个数组列表中没有不同项目的代码 [英] Code to determine no of different items in two arraylist

查看:56
本文介绍了确定两个数组列表中没有不同项目的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组列表,定义如下.

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");

我想知道上面两个 arraylist 的不同项的编号.为此,我有以下代码.

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 ?

推荐答案

你应该使用 Set 而不是 List.那么您要寻找的是对称差异.如果允许,您可以使用 Guava 的 Sets.symmetricDifference(Set, Set)

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)

这篇关于确定两个数组列表中没有不同项目的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆