Is there any equivalent of zip method from pyton in java?
a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica") x = zip(a, b) (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
Is there any equivalent of zip method from pyton in java?
a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica") x = zip(a, b) (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
The Guava library has a Streams.zip(Stream, Stream, BiFunction) method, which provides the same functionality as Python's zip function using the Stream API.
Here's the source code if you're curious:
public static <A extends @Nullable Object, B extends @Nullable Object, R extends @Nullable Object> Stream<R> zip( Stream<A> streamA, Stream<B> streamB, BiFunction<? super A, ? super B, R> function) { checkNotNull(streamA); checkNotNull(streamB); checkNotNull(function); boolean isParallel = streamA.isParallel() || streamB.isParallel(); // same as Stream.concat Spliterator<A> splitrA = streamA.spliterator(); Spliterator<B> splitrB = streamB.spliterator(); int characteristics = splitrA.characteristics() & splitrB.characteristics() & (Spliterator.SIZED | Spliterator.ORDERED); Iterator<A> itrA = Spliterators.iterator(splitrA); Iterator<B> itrB = Spliterators.iterator(splitrB); return StreamSupport.stream( new AbstractSpliterator<R>( min(splitrA.estimateSize(), splitrB.estimateSize()), characteristics) { @Override public boolean tryAdvance(Consumer<? super R> action) { if (itrA.hasNext() && itrB.hasNext()) { action.accept(function.apply(itrA.next(), itrB.next())); return true; } return false; } }, isParallel) .onClose(streamA::close) .onClose(streamB::close); } No, you'll have to create a map by looping the lists:
public Map<String, String> zip(List<String> a, List<String> b) { var map = new HashMap<String, String>(); for (var i = 0; i < a.size(); i++) { map.put(a.get(i), b.size() <= i ? b.get(i) : null); } return map; } zip, Indeed, in Python, zip is an iterator, so this would usually defeat the point anyway