I've got two List
objects and I want to pair them up, just like the zip()
function in Python. I'm pretty sure this isn't available in the JDK, but is there something like this in a fairly widespread library, similar to Apache Commons Collections? Thanks.
Even though there is no zip function in Java 8, we can use the map function to achieve the goal.
Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables. Suppose, two iterables are passed to zip() ; one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples.
If you want to include unmatched characters from the other two strings in the zipped object, use zip_longest() function defined in itertools module. Instead of None , any other character can be specified as fillvalue parameter. print(list(itertools.
Functional Java has zip
, zipWith
and zipIndex
the way you would expect from Haskell or Scala. (Indeed, the authors are pretty much all Haskell programmers.)
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