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}]
List<String> subjectArr = Arrays. asList("aa", "bb", "cc"); List<Long> numArr = Arrays. asList(2L, 6L, 4L); List<Pair> pairs = Streams. zip(subjectArr.
Even though there is no zip function in Java 8, we can use the map function to achieve the goal.
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.
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()); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With