Question: Zip and Pad Lists
Write a function named zipAndPad() that takes two lists of potentially different lengths as input. The function should return a list of pairs (as lists), where each pair consists of one element from each input list. If one list is longer than the other, pad the missing elements with an empty string.
Examples:
cust_id = { 1, 2, 3 };
cust_name = { "sam", "den", "lenny" };
customers = { {1,"sam"}, {2,"den"}, {3, "lenny"} };
Solution
In the below implementation, zipAndPad and remainingElements, work together to zip two lists into a list of paired elements, handling cases where the lists are of different lengths by padding missing elements.
<T, U> indicates that the method is generic, allowing you to pass in lists of any type (customerIds and customerNames can be of different types).
size calculation determines the length of the shorter list, ensuring we only iterate over the range where both lists have elements.
Zipping Elements:
for (int i = 0; i < size ; i++) iterates over both lists up to the
size
.zippedList.add(List.of(customerIds.get(i), customerNames.get(i)))
adds pairs of elements from the two lists to thezippedList
.remainingElements
Method Call:remainingElements(customerIds, customerNames, size, zippedList)
handles the remaining elements when the two lists are of different lengths (if any).
Tests:
Let's write some tests to verify if our zip implementation works correctly.
Conclusion
zipAndPad() function is useful for data alignment tasks, where two lists need to be combined while preserving all information, even if one list is shorter. It highlights the importance of using generic data structures and loop optimization, which are valuable skills for Java coding interviews.
Source Code is available here
Check out more java coding questions here.