Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip multiple lists using java 8?

Tags:

list

java-8

Given :

List<Integer> a = Arrays.asList(1,2,3);
List<Integer> b = Arrays.asList(1,2,3);
List<Integer> c = Arrays.asList(1,2,3);
List<Integer> d = Arrays.asList(1,2,3);

List<List<Integer>> sample = Arrays.asList(a,b,c,d);

How can I get this result with java 8?

[(1,1,1,1),(2,2,2,2),(3,3,3,3)]
like image 993
Will Avatar asked Jun 20 '17 12:06

Will


People also ask

How do I combine multiple lists into one in Java?

1. The addAll() method to merge two lists. The addAll() method is the simplest and most common way to merge two lists. Note the order of appearance of elements matches the order in which addAll() is called.

Is there a zip function in Java?

java. util. zip. ZipOutputStream can be used to compress a file into ZIP format.

How do I combine zip files in Java?

Get the name for the zip file to be created. Create a FileOutputStream object for the given zip name. Create a new ZipOutputStream object using the FileOutputStream object. Read the provided file and use the putNextEntry and write methods to add that file to the ZipOutputStream object.

What is Stream in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


2 Answers

/**
 * Zips lists. E.g. given [[1,2,3],[4,5,6]], returns [[1,4],[2,5],[3,6]].
 * @param listOfLists an N x M list
 * @returns an M x N list
 */
static <T> List<List<T>> zip(List<List<T>> listOfLists) {
    int size = listOfLists.get(0).size();
    List<List<T>> result = new ArrayList<>(size);
    for (int i = 0; i < size; ++i)
        result.add(
                listOfLists.stream()
                        .map(list -> list.get(i))
                        .collect(toList()));
    return result;
}
like image 117
Klitos Kyriacou Avatar answered Nov 15 '22 11:11

Klitos Kyriacou


Java streams don't natively support zipping.

If you want to do it manually, then using an IntStream as an 'iterator' over the lists is the way to go:

    List<Integer> l1 = Arrays.asList(1, 2, 3);
    List<Integer> l2 = Arrays.asList(2, 3, 4);

    List<Object[]> zipped = IntStream.range(0, 3).mapToObj(i -> new Object[]{l1.get(i), l2.get(i)}).collect(Collectors.toList());

    zipped.stream().forEach(i -> System.out.println(i[0] + " " + i[1]));

This is ugly, however, and not the 'java' way (as in using an array of 'properties' instead of a class).

like image 35
Jure Kolenko Avatar answered Nov 15 '22 09:11

Jure Kolenko