繁体   English   中英

有条件地遍历两个列表

[英]Iterate through two Lists with condition

问题:

我有两个按property列表排序的长度不同。 我需要创建两个结果列表,这些列表具有定义的记录计数并按property排序。 循环块中应该有一个条件,以验证应将哪条记录添加到结果列表中。

例如,两个按date属性按DESC顺序排序的列表:

list1: [{'1', '13:45:55', 'List1Title1'}, {'2', '13:40:50', 'List1Title2'}]

list2: [{'1', '13:50:55', 'List2Title1'}, {'2', '13:35:50', 'List2Title2'}]

对于count = 3,结果应类似于:

resultList1: [{'1', '13:45:55', 'List1Title1'}, {'2', '13:40:50', 'List1Title2'}]

resultList2: [{'1', '13:50:55', 'List2Title1'}]

我试图在for...帮助下遍历Lists并知道循环数:

List<Tx> list1 = ...;
List<Tx> list2 = ...;
int list1Index = 0;
int list2Index = 0;
for (int i = 0; i < count; i++) {
  if (list1.get(list1Index).getDate() > list2.get(list2Index).getDate()) {
      resultList1.add(list1.get(list1Index));
      ++list1Index;
    } else {
      resultList2.add(list2.get(list2Index));
      ++list2Index;
    }
}

但是,对于列表具有不同大小甚至为空的情况,此实现并不能节省。

没有大量的if/elseif块,是否有可能遍历这两个列表?

您可以添加到for ,如果有列表中的任意多个元素条件检查

for (int i = 0; i < count && i < list1.size() && i < list2.size(); i++) {
    \\ code here
}

并再添加两个for循环来处理剩余物

for (int i = 0; i < count && i < list1.size(); i++) {
    resultList1.add(list1.get(list1Index));
    ++list1Index;
}

for (int i = 0; i < count && i < list2.size(); i++) {
    resultList2.add(list2.get(list2Index));
    ++list2Index;
}

只有剩下任何元素时,才会执行这些循环。

循环直到selected == count或遍历list1list2

在循环,

  • 如果遍历了list1list2 ,则只需考虑左边的那个。
  • 如果不是,请比较它们并确定应增加哪个索引。

     int selected = 0; for (int list1Index = 0, list2Index = 0; selected < count && (list1Index < list1.size() || list2Index < list2.size()); selected++) { if (list1Index == list1.size()) { resultList2.add(list2.get(list2Index)); list2Index++; } else if (list2Index == list2.size()) { resultList1.add(list1.get(list1Index)); list1Index++; } else if (list1.get(list1Index).getDate() > list2.get(list2Index).getDate()) { resultList1.add(list1.get(list1Index)); list1Index++; } else { resultList2.add(list2.get(list2Index)); list2Index++; } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM