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 ae37cab

Browse files
Merge pull request #177 from davidanukam/patch-1
[Snippets] - add one very useful Java snippet
2 parents 3f3137a + 8f6de4d commit ae37cab

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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

Comments
(0)

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