1

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'))

Marek Borecki
  • 402
  • 1
  • 4
  • 20
  • 1
    There's this https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip – Kayaman Nov 24 '21 at 09:05
  • 1
    https://stackoverflow.com/questions/31963297/how-to-zip-two-java-lists – Guy Nov 24 '21 at 09:06
  • 1
    If they are always of same length, the simplest and most efficient would be creating the object you need with a for loop. – Equinox Nov 24 '21 at 09:07

2 Answers2

0

I found solution with IntStream

List<String> names1 = new ArrayList<>(Arrays.asList("John", "Charles", "Mike", "Dennis"));
List<String> names2 = new ArrayList<>(Arrays.asList("Jenny", "Christy", "Monica"));
IntStream
  .range(0, Math.min(names1.size(), names2.size()))
  .mapToObj(i -> names1.get(i) + ":" + names2.get(i))
  .toList();

But better looks solution with JOOL library

Seq
  .of("John","Charles", "Mike")
  .zip(Seq.of("Jenny", "Christy", "Monica"));
Marek Borecki
  • 402
  • 1
  • 4
  • 20
-1

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;
}
aiko
  • 423
  • 1
  • 4
  • 11
  • 1
    A map cannot contain duplicate keys, it is not a suitable substitute except in special cases for `zip`, Indeed, in Python, `zip` is an iterator, so this would usually defeat the point anyway – juanpa.arrivillaga Nov 24 '21 at 09:16