Home > OS >  zip method in java
zip method in java

Time:11-24

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

CodePudding user response:

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"));

CodePudding user response:

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;
}
  • Related