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));
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!