LearnFrenzy
Sign in Take a free test

Generics · Generics Programs · Question 6

Zip, unzip and group with a generic Pair in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write a generic Pair record and static generic methods zip(List<A>, List<B>) → List<Pair<A,B>> and unzipFirst, and use them to combine names with marks and find the topper.

Solution
Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

record Pair<A, B>(A first, B second) {
    @Override public String toString() { return first + ":" + second; }
}

public class Main {
    static <A, B> List<Pair<A, B>> zip(List<A> as, List<B> bs) {
        List<Pair<A, B>> out = new ArrayList<>();
        for (int i = 0; i < Math.min(as.size(), bs.size()); i++) out.add(new Pair<>(as.get(i), bs.get(i)));
        return out;
    }

    static <A, B> List<A> firsts(List<Pair<A, B>> pairs) {
        List<A> out = new ArrayList<>();
        for (Pair<A, B> p : pairs) out.add(p.first());
        return out;
    }

    public static void main(String[] args) {
        List<String> names = List.of("Asha", "Ravi", "Meena", "John");
        List<Integer> marks = List.of(91, 78, 95);
        List<Pair<String, Integer>> zipped = zip(names, marks);
        Pair<String, Integer> top = zipped.stream().max(Comparator.comparing(Pair::second)).orElseThrow();
        System.out.println(zipped + " top=" + top + " names=" + firsts(zipped));
    }
}

Output Verified by compiling and running

[Asha:91, Ravi:78, Meena:95] top=Meena:95 names=[Asha, Ravi, Meena]

Two type parameters keep both sides typed; zip stops at the shorter list, so John is dropped.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links