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:

4 tính chất của lập trình hướng đối tượng trong Java
Hướng dẫn sử dụng Printing Service trong Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Properties with Spring and Spring Boot
Different Ways to Capture Java Heap Dumps
Updating your Password
Registration – Activate a New Account by Email
How to Get All Dates Between Two Dates?
Spring Boot Actuator
Mệnh đề if-else trong java
Spring Boot Integration Testing with Embedded MongoDB
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
How to Remove the Last Character of a String?
Java Program to Implement Tarjan Algorithm
Reading an HTTP Response Body as a String in Java
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Implement Shell Sort
Auditing with JPA, Hibernate, and Spring Data JPA
Default Password Encoder in Spring Security 5
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Java – Write an InputStream to a File
Java Program to Implement Rolling Hash
Spring Boot - Sending Email
Java Program to Implement AA Tree
Jackson – Decide What Fields Get Serialized/Deserialized
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Working With Maps Using Streams
Create a Custom Exception in Java
Java Program to Implement Self organizing List
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself