2016-06-29 48 views
1

我有以下的数组列表比较两个数组列表

List<Long> ids = new ArrayList<Long>(); 
List<Long> empIds = new ArrayList<Long>(); 

现在我需要比较这2个阵列和检查,如果在IDS的任何值有在empIds。如果是,我需要用布尔值true来退出。我通过以下方式完成了这项工作。

for (Long id : ids) { 
    if (empIds.contains(id)) { 
     checker = true; 
     break; 
    } 
} 

但这需要很多时间。任何人都可以帮我优化这个吗?

+0

数组的大小是多少?并请分享一些时间输出。 我不认为有一个更简单的方法 –

+0

ids或empIds排序或几乎排序? –

回答

4

你可以把empIdsHashSet改善搜索时间:

Set<Long> empIdsSet = new HashSet<Long>(empIds); 
for (Long id : ids) { 
    if (empIdsSet.contains(id)) { 
     checker = true; 
     break; 
    } 
} 

empIdsSet.contains(id)每次通话将采取预期的固定时间(O(1)),这比每次调用empIds.contains(id)所需的线性时间更好。

+1

这会假定散列列表所需的时间并不重要。 –

+2

@TimBiegeleisen散列列表的时间是线性的,所以整体时间仍然比原始代码更好。 – Eran

+1

太糟糕了,这被标记为重复。这个解决方案的执行速度比'Collections.disjoint'快得多(可能以二次方式运行 - 类似于OP的代码) –