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:

Converting a Stack Trace to a String in Java
Java Program to Implement Iterative Deepening
Phương thức forEach() trong java 8
Spring Data JPA @Modifying Annotation
Overflow and Underflow in Java
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Find the Registered Spring Security Filters
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java Program to Decode a Message Encoded Using Playfair Cipher
Spring Boot - Scheduling
Marker Interface trong Java
Java Program to Implement Jarvis Algorithm
Hướng dẫn Java Design Pattern – MVC
Spring Security – security none, filters none, access permitAll
Java Program to Perform String Matching Using String Library
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Primitive Type Streams in Java 8
Working with Network Interfaces in Java
@Order in Spring
Extra Login Fields with Spring Security
Introduction to Spring Security Expressions
HttpClient with SSL
Feign – Tạo ứng dụng Java RESTful Client
Java Program to Implement the Checksum Method for Small String Messages and Detect
Java Program to Describe the Representation of Graph using Adjacency List
Java Program to Create a Random Linear Extension for a DAG
Java Program to Describe the Representation of Graph using Incidence Matrix
Pagination and Sorting using Spring Data JPA
Java Program to Implement Sorted Circularly Singly Linked List
Java Program to Implement Merge Sort Algorithm on Linked List
Overview of the java.util.concurrent