Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snippets] - add one very useful Java snippet #177

Merged
merged 3 commits into from
Jan 5, 2025
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions snippets/java/array-manipulation/zip-two-lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
title: Zip Two Lists
description: Zips two lists into a list of paired elements, combining corresponding elements from both lists.
author: davidanukam
tags: lists,zip,stream-api,collections
---

```java
import java.util.*; // Importing utility classes for List and Arrays
import java.util.stream.IntStream; // Importing IntStream for range and mapping
import java.util.stream.Collectors; // Importing Collectors for collecting stream results

public class Main {
Mathys-Gasnier marked this conversation as resolved.
Show resolved Hide resolved
// Generic method to zip two lists into a list of paired elements
public static <A, B> List<List<Object>> zip(List<A> list1, List<B> list2) {
// Create pairs by iterating through the indices of both lists
return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list
.mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i
.collect(Collectors.toList()); // Collect the pairs into a List
}

public static void main(String[] args) {
// Usage:
List<String> arr1 = Arrays.asList("a", "b", "c");
List<Integer> arr2 = Arrays.asList(1, 2, 3);
List<List<Object>> zipped = zip(arr1, arr2);

System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]
}
}
```