Java Generic Methods
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:
lastOflinks its input and output types: whatever element type the list has, the method returns that type. With aList<Integer>it returnsInteger, unboxed tointon assignment. A non-generic version returningObjectwould force every caller to cast.repeatinfersTfrom the value:"-"givesList<String>,'*'(achar, boxed) givesList<Character>.inverthas two type parameters and swaps their roles in the result: aMap<String, Integer>becomes aMap<Integer, String>, sobyNumber.get(102)is known to be aStringand.toLowerCase()compiles. (If two keys had the same value, the later one would win, because map keys are unique.)- 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. - 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]
@SafeVarargsis the author's promise that the method only reads the varargs array and doesn't let it escape.listOfcopies the elements into a new list, so it's safe, and the annotation removes the warning for the method and all its callers.unsafereturns the array itself, which can lead to an array whose runtime type (Object[]) doesn't match what callers expect, causing aClassCastExceptionfar from the cause. It deserves the warning; don't annotate such methods.@SafeVarargsis allowed only on methods that can't be overridden:static,final,privatemethods and constructors.
Generic Methods versus Generic Classes
Generic class class Box<T> | Generic method static <T> T lastOf(List<T>) | |
|---|---|---|
| Type parameter scope | The whole class — fields and all methods | That one method |
| Type argument chosen | When the object is created (new Box<String>()) | At each call (usually inferred) |
| Use when | The object holds or works with values of the type over its lifetime | A single operation must work for any type |
| Static use | Static members can't use T | Static 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:
firstMatch(Collection<T>, Predicate<T>)returnsOptional<T>. TheTin the predicate ties the condition to the element type: for orders, the lambda's parameterois anOrder, soo.amount()compiles; for strings,sis aString. The result type follows automatically —Optional<Order>orOptional<String>.groupBy(Collection<T>, Function<T, K>)has two type parameters:Tfor the elements andKfor the grouping key, which is whatever the key function returns.Order::cityproducesStringkeys;String::lengthproducesIntegerkeys. The result typeMap<K, List<T>>is precise in both cases.computeIfAbsentcreates each group's list the first time its key appears, and theTreeMapkeeps keys sorted.retry(int, Supplier<T>)runs an action up toattemptstimes and returns its result.Tis inferred from what the lambda returns:"PAID"makes itString;40makes itInteger, which is whystock + 1works. 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.