# Iterate through two Lists with condition

Problem:

I have two sorted by a `property` Lists with different length. I need to create two resulting Lists with a defined records count and sorted by the `property`. There should be a condition in a loop block to verify which record should be added to the resulting list.

For example, two lists sorted by `date` property in `DESC` order:

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

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

For count = 3, result should look like:

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

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

I've tried to iterate through Lists with help of the `for...` with known loops count:

``````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()) {
++list1Index;
} else {
++list2Index;
}
}
``````

But this implementation isn't save for cases when lists have a different size or even are empty.

Is there a possibility to iterate over these two Lists without a large amount of `if/elseif` blocks?

You can add to the `for` condition check if the there are any more elements in the list

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

And add two more for loop to handle the leftovers

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

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

Those loops will be executed only if there are any elements left.

Loop until `selected == count` or both `list1` and `list2` have been traversed.

In the loop,

• If `list1` or `list2` has been traversed, then just consider the left one.
• If not, compare them and determine which index should be incremented.

``````int selected = 0;

for (int list1Index = 0, list2Index = 0;
selected < count && (list1Index < list1.size() || list2Index < list2.size());
selected++) {
if (list1Index == list1.size()) {