Java Generic Methods

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 161 of 306

What a Generic Method Is

A generic method declares its own type parameters, independent of any class. The type parameter list goes in angle brackets before the return type:

static <T> T lastOf(List<T> list) { ... }
//     ^^^ type parameter declaration
//         ^ return type uses it
//                  ^^^^^^^ parameter type uses it

The method can be static or an instance method, and the class it's in doesn't need to be generic. Each call gets its own type argument, usually inferred by the compiler from the arguments:

String s = lastOf(List.of("a", "b"));   // T is inferred as String
int n    = lastOf(List.of(1, 2, 3));     // T is inferred as Integer

Generic methods are the right tool for utility operations that work on many types — finding, grouping, copying, converting, retrying — where making a whole class generic would be unnecessary. Much of the JDK is built this way: Collections.sort, List.of, Arrays.asList, Objects.requireNonNull, Optional.of, Map.entry and Stream.map are all generic methods.

Writing and Calling Generic Methods

import java.util.*;

public class M1 {
    static <T> T lastOf(List<T> list) {
        if (list.isEmpty()) throw new NoSuchElementException("empty list");
        return list.get(list.size() - 1);
    }

    static <T> List<T> repeat(T value, int times) {
        List<T> result = new ArrayList<>(times);
        for (int i = 0; i < times; i++) result.add(value);
        return result;
    }

    static <K, V> Map<V, K> invert(Map<K, V> map) {
        Map<V, K> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> e : map.entrySet()) result.put(e.getValue(), e.getKey());
        return result;
    }

    public static void main(String[] args) {
        String lastCity = lastOf(List.of("Chennai", "Madurai", "Salem"));
        int lastScore = lastOf(List.of(91, 78, 85));
        System.out.println(lastCity + " " + lastScore);

        List<String> dashes = repeat("-", 3);
        List<Character> stars = repeat('*', 2);
        System.out.println(dashes + " " + stars);

        Map<String, Integer> codes = new LinkedHashMap<>(Map.of("JAVA", 101));
        codes.put("PY", 102);
        Map<Integer, String> byNumber = invert(codes);
        System.out.println(byNumber + " -> " + byNumber.get(102).toLowerCase());

        List<String> empty = M1.<String>repeat("x", 0);
        System.out.println("explicit type witness: " + empty);
        List<String> none = Collections.emptyList();
        System.out.println("inferred from target: " + none.size());
    }
}

Output:

Salem 85
[-, -, -] [*, *]
{101=JAVA, 102=PY} -> py
explicit type witness: []
inferred from target: 0

What each method shows:

  1. lastOf links its input and output types: whatever element type the list has, the method returns that type. With a List<Integer> it returns Integer, unboxed to int on assignment. A non-generic version returning Object would force every caller to cast.
  2. repeat infers T from the value: "-" gives List<String>, '*' (a char, boxed) gives List<Character>.
  3. invert has two type parameters and swaps their roles in the result: a Map<String, Integer> becomes a Map<Integer, String>, so byNumber.get(102) is known to be a String and .toLowerCase() compiles. (If two keys had the same value, the later one would win, because map keys are unique.)
  4. An explicit type witness: M1.<String>repeat("x", 0) states the type argument instead of letting the compiler infer it. The syntax requires a qualifier before the dot — the class name for static methods, this. or a variable for instance methods. It's rarely needed.
  5. Inference from the target type: Collections.emptyList() has no arguments to infer from, so the compiler uses the type of the variable being assigned (List<String>).

How Type Inference Works

The compiler infers type arguments from two sources:

  • The arguments passed to the method (lastOf(List.of("a")) → T = String).
  • The target type — what the result is assigned to or returned as (List<String> none = Collections.emptyList()).

When arguments have different types, the compiler looks for the most specific type they have in common:

static <T> T pick(T a, T b) { return a; }

var mixed = pick("text", 42);              // T is a common supertype of String and Integer
Comparable<?> c = pick("text", 42);        // fine: both are Comparable
String s = pick("text", 42);               // compile error

The last line fails because no single T can be both a String (required by the assignment) and a supertype of Integer. The compiler's message mentions an intersection type — a type such as Object & Serializable & Comparable<...> that it inferred as the common supertype — and explains that it doesn't conform to String. Messages like this look intimidating, but they almost always mean "the arguments don't share the type you expected". Mixing unrelated types in one call usually signals a bug.

Generic Methods with Varargs

A generic method can take a variable number of arguments (T... items), which is how List.of, Set.of and Arrays.asList are declared. Internally, varargs are passed as an array, and since arrays of a type parameter can't be created safely (Generic Types lesson), the compiler warns:

import java.util.*;

public class Var {
    @SafeVarargs
    static <T> List<T> listOf(T... items) {
        return new ArrayList<>(Arrays.asList(items));
    }

    static <T> T[] unsafe(T... items) {
        return items;
    }

    public static void main(String[] args) {
        List<String> langs = listOf("Java", "Python", "Go");
        langs.add("Rust");
        System.out.println(langs);

        List<Integer> one = listOf(7);
        System.out.println(one);
    }
}

Compiled with javac -Xlint:unchecked:

Var.java:9: warning: [unchecked] Possible heap pollution from parameterized vararg type T
    static <T> T[] unsafe(T... items) {
                               ^
  where T is a type-variable:
    T extends Object declared in method <T>unsafe(T...)
1 warning

Output:

[Java, Python, Go, Rust]
[7]
  • @SafeVarargs is the author's promise that the method only reads the varargs array and doesn't let it escape. listOf copies the elements into a new list, so it's safe, and the annotation removes the warning for the method and all its callers.
  • unsafe returns the array itself, which can lead to an array whose runtime type (Object[]) doesn't match what callers expect, causing a ClassCastException far from the cause. It deserves the warning; don't annotate such methods.
  • @SafeVarargs is allowed only on methods that can't be overridden: static, final, private methods and constructors.

Generic Methods versus Generic Classes

Generic class class Box<T>Generic method static <T> T lastOf(List<T>)
Type parameter scopeThe whole class — fields and all methodsThat one method
Type argument chosenWhen the object is created (new Box<String>())At each call (usually inferred)
Use whenThe object holds or works with values of the type over its lifetimeA single operation must work for any type
Static useStatic members can't use TStatic methods can declare their own T

A generic class can also contain generic methods with additional type parameters — like PageOf<T>.map(Function<T, R>) in the Generics Intro lesson, which introduces R just for that method.

Practical Example: A Utility Toolkit

Applications accumulate small helper methods that work on many types. Written as generic methods, each is written and tested once and then used with orders, users, strings and anything else, with full type checking.

import java.util.*;
import java.util.function.*;

public class Util {
    static <T> Optional<T> firstMatch(Collection<T> items, Predicate<T> condition) {
        for (T item : items) {
            if (condition.test(item)) return Optional.of(item);
        }
        return Optional.empty();
    }

    static <T, K> Map<K, List<T>> groupBy(Collection<T> items, Function<T, K> keyOf) {
        Map<K, List<T>> groups = new TreeMap<>();
        for (T item : items) {
            groups.computeIfAbsent(keyOf.apply(item), k -> new ArrayList<>()).add(item);
        }
        return groups;
    }

    static <T> T retry(int attempts, Supplier<T> action) {
        RuntimeException last = null;
        for (int i = 1; i <= attempts; i++) {
            try {
                return action.get();
            } catch (RuntimeException e) {
                last = e;
                System.out.println("  attempt " + i + " failed: " + e.getMessage());
            }
        }
        throw new IllegalStateException("gave up after " + attempts + " attempts", last);
    }

    record Order(String id, String city, double amount) { }

    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("O-1", "Chennai", 2500), new Order("O-2", "Madurai", 800),
            new Order("O-3", "Chennai", 12000), new Order("O-4", "Salem", 450));

        Optional<Order> big = firstMatch(orders, o -> o.amount() > 10_000);
        System.out.println("first big order: " + big.map(Order::id).orElse("none"));
        Optional<String> longName = firstMatch(List.of("Ravi", "Meenakshi"), s -> s.length() > 6);
        System.out.println("first long name: " + longName.orElse("none"));

        Map<String, List<Order>> byCity = groupBy(orders, Order::city);
        byCity.forEach((city, list) -> System.out.println(city + ": " + list.stream().map(Order::id).toList()));
        Map<Integer, List<String>> byLength = groupBy(List.of("pen", "ink", "book", "bag"), String::length);
        System.out.println(byLength);

        int[] calls = {0};
        String status = retry(3, () -> {
            if (++calls[0] < 3) throw new IllegalStateException("gateway busy");
            return "PAID";
        });
        System.out.println("payment status: " + status);
        int stock = retry(2, () -> 40);
        System.out.println("stock: " + (stock + 1));
    }
}

Output:

first big order: O-3
first long name: Meenakshi
Chennai: [O-1, O-3]
Madurai: [O-2]
Salem: [O-4]
{3=[pen, ink, bag], 4=[book]}
  attempt 1 failed: gateway busy
  attempt 2 failed: gateway busy
payment status: PAID
stock: 41

How each method uses its type parameters:

  1. firstMatch(Collection<T>, Predicate<T>) returns Optional<T>. The T in the predicate ties the condition to the element type: for orders, the lambda's parameter o is an Order, so o.amount() compiles; for strings, s is a String. The result type follows automatically — Optional<Order> or Optional<String>.
  2. groupBy(Collection<T>, Function<T, K>) has two type parameters: T for the elements and K for the grouping key, which is whatever the key function returns. Order::city produces String keys; String::length produces Integer keys. The result type Map<K, List<T>> is precise in both cases. computeIfAbsent creates each group's list the first time its key appears, and the TreeMap keeps keys sorted.
  3. retry(int, Supplier<T>) runs an action up to attempts times and returns its result. T is inferred from what the lambda returns: "PAID" makes it String; 40 makes it Integer, which is why stock + 1 works. If every attempt fails, the last exception is attached as the cause (Exception Chaining lesson).

The Stream API provides built-in versions of some of these (stream().filter(...).findFirst(), Collectors.groupingBy), and they're declared as generic methods in exactly the same way. Reading their signatures — for example static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier) — becomes much easier once you've written methods like these yourself. The ? super and ? extends parts are wildcards, which make such methods even more flexible; they're explained in the Wildcards lesson.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Generic Methods and get answers drawn from it.

Signed-in readers only.