How to create a generic method with multiple type parameters in Java

1 Answer

0 votes
// Generic Pair Printing Using a Generic Method in Java

public class Main {

    // Generic method with two type parameters
    public static <K, V> void printPair(K key, V value) {
        System.out.println(key + " = " + value);
    }

    public static void main(String[] args) {

        // Using different types for K and V
        printPair("Age", 30);
        printPair(101, "Employee ID");
        printPair("Pi", 3.14159);
        printPair(true, "Boolean Key");
        printPair("Language", "Java");

        // Using custom objects
        printPair("Point", new Point(10, 20));
    }
}

// Simple custom class for demonstration
class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}



/*
run:

Age = 30
101 = Employee ID
Pi = 3.14159
true = Boolean Key
Language = Java
Point = (10, 20)

*/

 



answered 16 hours ago by avibootz
...