Zipping Collections in Java

1. Introduction

In this tutorial, we’ll illustrate how to zip two collections into one logical collection.

The “zip” operation is slightly different from the standard “concat” or “merge”. While the “concat” or “merge” operations will simply add the new collection at the end of the existing collection, “zip” operation will take an element from each collection and combine them.

The core library does not support “zip” implicitly, but there are certainly third-party libraries which do feature this useful operation.

Consider two lists, one having names of people, other contains their ages.

List<String> names = new ArrayList<>(Arrays.asList("John", "Jane", "Jack", "Dennis"));

List<Integer> ages = new ArrayList<>(Arrays.asList(24, 25, 27));

After zipping, we end up with name-age pairs constructed from corresponding elements from those two collections.

2. Using Java 8 IntStream

Using core Java, we could generate indexes using IntStream and then use them to extract corresponding elements from two collections:

IntStream
  .range(0, Math.min(names.size(), ages.size()))
  .mapToObj(i -> names.get(i) + ":" + ages.get(i))
  // ...

3. Using Guava Streams

Starting version 21, Google Guava provides a zip helper method in the Streams class. This removes all the fuss of creating and mapping indexes and reduces the syntax to inputs and operations:

Streams
  .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
  // ...

4. Using jOOλ (jOOL)

jOOL also provides some of the fascinating additions over Java 8 Lambda, and with the support of Tuple1 to Tuple16, the zip operation becomes much more interesting:

Seq
  .of("John","Jane", "Dennis")
  .zip(Seq.of(24,25,27));

This will produce a result of a Seq containing Tuples of zipped elements:

(tuple(1, "a"), tuple(2, "b"), tuple(3, "c"))

jOOL’s zip method gives the flexibility to provide custom transformation function:

Seq
  .of(1, 2, 3)
  .zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y);

or if one wishes to zip with index only, he can go with the zipWithIndex method provided by jOOL:

Seq.of("a", "b", "c").zipWithIndex();

5. Conclusion

In this quick tutorial, we had a look at how to perform the zip operation.

As always, the code examples in the article can be found over on GitHub.

Related posts:

Introduction to the Java NIO2 File API
Java Program to Implement Ternary Tree
Using Spring @ResponseStatus to Set HTTP Status Code
ETL with Spring Cloud Data Flow
Default Password Encoder in Spring Security 5
Java Map With Case-Insensitive Keys
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Spring Security Registration – Resend Verification Email
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Java – Reader to Byte Array
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Check whether Directed Graph is Connected using DFS
Serialize Only Fields that meet a Custom Criteria with Jackson
Java Program to Solve any Linear Equation in One Variable
How to Read HTTP Headers in Spring REST Controllers
SOAP Web service: Authentication trong JAX-WS
Java Program to Perform Sorting Using B-Tree
Vòng lặp for, while, do-while trong Java
Java Program to Represent Graph Using Linked List
Consumer trong Java 8
Mapping Nested Values with Jackson
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Perform Right Rotation on a Binary Search Tree
Java Program to Perform Searching Using Self-Organizing Lists
Java Program to Compute the Area of a Triangle Using Determinants
Transactions with Spring and JPA
Java Program to Implement Find all Forward Edges in a Graph
Java – Rename or Move a File
Spring Boot - Apache Kafka
Java Program to Implement Skew Heap
Hướng dẫn Java Design Pattern – Proxy
REST Web service: Upload và Download file với Jersey 2.x