Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip two Java Lists

Tags:

java

arraylist

I have 2 Lists:

List<String> subjectArr = Arrays.asList<String>("aa", "bb", "cc"); List<Long> numArr = Arrays.asList<Long>(2L, 6L, 4L); 

How do I create new List and zip two Lists into it?

List<?> subjectNumArr = zip(subjectArr, numArr); // subjectNumArr == [{'aa',2},{'bb',6},{'cc',4}] 
like image 345
ahad bahmanian Avatar asked Aug 12 '15 11:08

ahad bahmanian


People also ask

How to zip two List in Java?

List<String> subjectArr = Arrays. asList("aa", "bb", "cc"); List<Long> numArr = Arrays. asList(2L, 6L, 4L); List<Pair> pairs = Streams. zip(subjectArr.

Is there a zip function in Java?

Even though there is no zip function in Java 8, we can use the map function to achieve the goal.

How can I zip a file in Java?

Steps to Compress a File in JavaPut a ZipEntry object by calling the putNextEntry(ZipEntry) method on the ZipOutputStream. The ZipEntry class represents an entry of a compressed file in the ZIP file. Read all bytes from the original file by using the Files. readAllBytes(Path) method.


2 Answers

Here's Java-8 solution using the Pair class (like in @ZhekaKozlov answer):

public static <A, B> List<Pair<A, B>> zipJava8(List<A> as, List<B> bs) {     return IntStream.range(0, Math.min(as.size(), bs.size()))             .mapToObj(i -> new Pair<>(as.get(i), bs.get(i)))             .collect(Collectors.toList()); } 

In Java 9 onwards you can use Map.entry():

    public static <A, B> List<Map.Entry<A, B>> zipJava8(List<A> as, List<B> bs) {         return IntStream.range(0, Math.min(as.size(), bs.size()))                 .mapToObj(i -> Map.entry(as.get(i), bs.get(i)))                 .collect(Collectors.toList());     } 
like image 187
Tagir Valeev Avatar answered Sep 20 '22 14:09

Tagir Valeev


As per related question, you can use Guava (>= 21.0) to do this:

List<String> subjectArr = Arrays.asList("aa", "bb", "cc"); List<Long> numArr = Arrays.asList(2L, 6L, 4L); List<Pair> pairs = Streams.zip(subjectArr.stream(), numArr.stream(), Pair::new)         .collect(Collectors.toList()); 

Note that the guava method is annotated as @Beta, though what that means in practice is up to interpretation, the method has not changed since version 21.0.

like image 36
tkruse Avatar answered Sep 18 '22 14:09

tkruse