Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2d1216f

Browse files
Create zip-two-lists.md
1 parent 11625c1 commit 2d1216f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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,java,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 class Main {
14+
// Generic method to zip two lists into a list of paired elements
15+
public static <A, B> List<List<Object>> zip(List<A> list1, List<B> list2) {
16+
// Create pairs by iterating through the indices of both lists
17+
return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list
18+
.mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i
19+
.collect(Collectors.toList()); // Collect the pairs into a List
20+
}
21+
22+
public static void main(String[] args) {
23+
// Usage:
24+
List<String> arr1 = Arrays.asList("a", "b", "c");
25+
List<Integer> arr2 = Arrays.asList(1, 2, 3);
26+
List<List<Object>> zipped = zip(arr1, arr2);
27+
28+
System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]
29+
}
30+
}
31+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /