|
| 1 | +--- |
| 2 | +title: Zip Two Lists |
| 3 | +description: Zips two lists into a list of paired elements, combining corresponding elements from both lists. |
| 4 | +author: davidanukam |
| 5 | +tags: lists,zip,stream-api,collections |
| 6 | +--- |
| 7 | + |
| 8 | +```java |
| 9 | +import java.util.*; // Importing utility classes for List and Arrays |
| 10 | +import java.util.stream.IntStream; // Importing IntStream for range and mapping |
| 11 | +import java.util.stream.Collectors; // Importing Collectors for collecting stream results |
| 12 | + |
| 13 | +public <A, B> List<List<Object>> zip(List<A> list1, List<B> list2) { |
| 14 | + // Create pairs by iterating through the indices of both lists |
| 15 | + return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list |
| 16 | + .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i |
| 17 | + .collect(Collectors.toList()); // Collect the pairs into a List |
| 18 | +} |
| 19 | + |
| 20 | +// Usage: |
| 21 | +List<String> arr1 = Arrays.asList("a", "b", "c"); |
| 22 | +List<Integer> arr2 = Arrays.asList(1, 2, 3); |
| 23 | +List<List<Object>> zipped = zip(arr1, arr2); |
| 24 | + |
| 25 | +System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]] |
| 26 | +``` |
0 commit comments