我想迭代2个集合,每个集合大约600条记录。我想比较集合1的每个元素与集合2中的所有其他元素。如果我选择我的集合为LinkedHashSet,那么我必须在每个集合上调用迭代器并且有两个while(内部和外部)循环。对于ArrayList的选择,我将有两个for循环(内部和外部)来从每个集合中读取数据。
主要是我选择LinkedHashSet,因为我读到LinkedHashSet有更好的性能,我也更喜欢使用set来删除重复,但看到它运行速度很慢,花了大约2个小时才完成,我想也许最好将set复制到一个然后使用ArrayList迭代ArrayList而不是LinkedHashSet。我想知道哪一个会有更好的选择来加速运行时。
public ArrayList> processDataSourcesV2(LinkedHashMap> ppmsFinalResult,LinkedHashMap> productDBFinalResult){//每个参数都是一个包含key(id)和value(唯一参数集)的hashmap ArrayList> result = new ArrayList>();
Iterator<Entry<RecordId, LinkedHashSet<String>>> ppmsIterator = ppmsFinalResult.entrySet().iterator();
Iterator<Entry<RecordId, LinkedHashSet<String>>> productIdIterator =null;
//pair of id from each list
ArrayList<Pair> listOfIdPair = new ArrayList<Pair>();
while (ppmsIterator.hasNext()) {
//RecordId object is an object containing the id and which list this id belongs to
Entry<RecordId, LinkedHashSet<String>> currentPpmsPair = ppmsIterator.next();
RecordId currentPpmsIDObj = currentPpmsPair.getKey();
//set of unique string
LinkedHashSet<String> currentPpmsCleanedTerms = (LinkedHashSet<String>)currentPpmsPair.getValue();
productIdIterator = productDBFinalResult.entrySet().iterator();
while (productIdIterator.hasNext()) {
Entry<RecordId, LinkedHashSet<String>> currentProductDBPair = productIdIterator.next();
RecordId currentProductIDObj = currentProductDBPair.getKey();
LinkedHashSet<String> currentProductCleanedTerms = (LinkedHashSet<String>)currentProductDBPair.getValue();
ArrayList<Object> listOfRowByRowProcess = new ArrayList <Object>();
Pair currentIDPair = new Pair(currentPpmsIDObj.getIdValue(),currentProductIDObj.getIdValue());
//check for duplicates
if ((currentPpmsIDObj.getIdValue()).equals(currentProductIDObj.getIdValue()) || listOfIdPair.contains(currentIDPair.reverse()) ) {
continue;
}
else {
LinkedHashSet<String> commonTerms = getCommonTerms(currentPpmsCleanedTerms,currentProductCleanedTerms);
listOfIdPair.add(currentIDPair.reverse());
if (commonTerms.size()>0) {
listOfRowByRowProcess.add(currentPpmsIDObj);
listOfRowByRowProcess.add(currentProductIDObj);
listOfRowByRowProcess.add(commonTerms);
result.add(listOfRowByRowProcess);
}
}
}
}
return result;
}
public LinkedHashSet<String> getCommonTerms(LinkedHashSet<String> setOne, LinkedHashSet<String> setTwo){
Iterator<String> setOneIt = setOne.iterator();
LinkedHashSet<String> setOfCommon = new LinkedHashSet<String>();
//making hard copy
while (setOneIt.hasNext()) {
setOfCommon.add(setOneIt.next());
}
setOfCommon.retainAll(setTwo);
return setOfCommon;
}
在迭代时,数组比任何其他结构都要快(所有元素都按顺序存储在内存中),另一方面,删除和插入元素时速度较慢,因为它必须确保顺序存储。对链表进行迭代的速度较慢,因为您可能会出现页面错误...因此,您可以选择哪一个。
如果要查找两个集合中的哪些元素,请将其设为Set
并与其他集合进行交集:
Collection<T> collection1, collection2; // given these
Set<T> intersection = new HashSet<T>(collection1);
intersection.retainAll(collection2);
这将在O(n)时间内执行,其中n
是collection2
的大小,因为在HashSet
中查找元素在恒定时间内执行。
我的猜测是你用collection1
的每个元素检查collection2
的每个元素,它具有O(n2)时间复杂度。