Java — Lets learn few features…Generics
Let’s take a real-world scenario and build around it to explain Java Generics along with related Java concepts where generics are used. The idea is to build a comprehensive, relatable example while covering the breadth of generics in Java.
Real-World Scenario: Online Grocery Store
We’ll use an online grocery store example. The store deals with different types of products: fruits, vegetables, packaged items, etc. Each item has a price, a name, and sometimes expiry dates or categories.
Java Concepts Covered:
- Generic Classes
- Generic Methods
- Bounded Type Parameters
- Wildcards (
?,<? extends T>,<? super T>) - Generics with Collections (e.g.,
List<T>) - Inheritance and Generics
- Custom Comparator with Generics
- Type Erasure (brief mention)
public class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
// Usage
Box<String> stringBox = new Box<>();
stringBox.setItem("Apple");
Box<Integer> weightBox = new Box<>();
weightBox.setItem(5); // e.g., 5 kg of riceGeneric Method
public class Utils {
public static <T> boolean isEqual(T a, T b) {
return a.equals(b);
}
}
// Usage
boolean result = Utils.isEqual("Milk", "Milk"); // trueBounded Type Parameters
Suppose we want to restrict types to only those that are Product or its subclasses.
public class Product {
String name;
double price;
// constructors, getters
}
public class Fruit extends Product {
String type;
// constructors, extra fields
}
public class Inventory<T extends Product> {
private List<T> items = new ArrayList<>();
public void addItem(T item) {
items.add(item);
}
public double totalValue() {
return items.stream().mapToDouble(Product::getPrice).sum();
}
}
// Usage
Inventory<Fruit> fruitInventory = new Inventory<>();
fruitInventory.addItem(new Fruit("Apple", 2.5, "Organic"));Wildcards
a. Upper Bound (<? extends Product>)
To read from a list of any product type safely:
public static void printPrices(List<? extends Product> products) {
for (Product p : products) {
System.out.println(p.getPrice());
}
}b. Lower Bound (<? super Fruit>)
To add fruits to a list that accepts any superclass of Fruit:
public static void addFruit(List<? super Fruit> list) {
list.add(new Fruit("Banana", 1.2, "Cavendish"));
}Generics with Collections
Collections like List<T>, Map<K, V>, Set<T> are generic.
List<Product> cart = new ArrayList<>();
cart.add(new Fruit("Mango", 3.0, "Alphonso"));
Map<String, List<Product>> categoryMap = new HashMap<>();
categoryMap.put("Fruits", cart);Inheritance with Generics
public class DiscountedBox<T extends Product> extends Box<T> {
private double discount;
public double getDiscountedPrice() {
return getItem().getPrice() * (1 - discount);
}
}Comparator with Generics
// Sorting
public class ProductComparator<T extends Product> implements Comparator<T> {
public int compare(T p1, T p2) {
return Double.compare(p1.getPrice(), p2.getPrice());
}
}
Collections.sort(productList, new ProductComparator<>());Example
Inventory<Fruit> fruitInventory = new Inventory<>();
fruitInventory.addItem(new Fruit("Apple", 1.5, "Organic"));
fruitInventory.addItem(new Fruit("Orange", 2.0, "Mandarin"));
Inventory<Vegetable> vegInventory = new Inventory<>();
vegInventory.addItem(new Vegetable("Carrot", 0.9));
Utils.printPrices(fruitInventory.getItems()); // Using upper bound wildcard
List<Product> combined = new ArrayList<>();
combined.addAll(fruitInventory.getItems());
combined.addAll(vegInventory.getItems());
Collections.sort(combined, new ProductComparator<>());
DiscountedBox<Fruit> offer = new DiscountedBox<>();
offer.setItem(new Fruit("Kiwi", 2.5, "Green"));
offer.setDiscount(0.2); // 20% offWhy Generics Are Still Needed (Even With Streams and Lambdas)
Streams use generics heavily
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);Stream<String>here means the compiler knows what type it’s working with at each stage.- Without generics, you’d need manual casting and runtime checks — which generics save you from.
Collections and APIs are generics-based
Even modern patterns like functional programming build on generics.
Get Naveen’s stories in your inbox
Join Medium for free to get updates from this writer.
Example: Optional<T>, Function<T, R>, Predicate<T>, Comparator<T> — these are all generic interfaces.
Optional<Integer> value = Optional.of(42);
Function<String, Integer> parseInt = Integer::parseInt;
Predicate<String> isLongName = name -> name.length() > 5;Custom Reusable Utilities Still Require Generics
Streams solve many cases for data processing, but when you write reusable, type-safe utilities or components — you need generics.
Example: sorting logic, custom data containers, utilities that work with multiple types.
public static <T extends Comparable<T>> T max(List<T> list) {
return list.stream().max(Comparator.naturalOrder()).orElse(null);
}Streams don’t eliminate type hierarchies
You still need:
- Generic classes (
class Box<T>) - Bounded generics (
<T extends Product>) - Wildcards (
<? extends T>,<? super T>) - Inheritance and generic APIs
None of that is replaced by streams — streams complement this by offering processing pipelines.
Real-World Frameworks Still Rely on Generics
Frameworks like:
- Spring (e.g.
JpaRepository<T, ID>) - Jackson (e.g.
TypeReference<List<MyClass>>) - RxJava, Project Reactor, MapStruct, Guava
All use generics deeply for flexibility, reusability, and safety.
Where Streams Do Reduce the Need for Some Generics
Example 1: No need for utility classes like
ListUtils<T>
// Before
public class ListUtils {
public static <T> void print(List<T> list) {
for (T item : list) System.out.println(item);
}
}
// After
list.forEach(System.out::println);Example 2: Less need for custom filters or transformers
// Before
public static <T> List<T> filter(List<T> list, Predicate<T> pred) { ... }
// After
list.stream().filter(pred).collect(Collectors.toList());Older utility-style generics vs modern Java with Streams and Lambdas
Filtering Items by Price
// Before
public static <T> List<T> filter(List<T> list, Predicate<T> predicate) {
List<T> result = new ArrayList<>();
for (T item : list) {
if (predicate.test(item)) {
result.add(item);
}
}
return result;
}
// Usage
List<Product> cheapItems = filter(products, p -> p.getPrice() < 10);
// After
List<Product> cheapItems = products.stream()
.filter(p -> p.getPrice() < 10)
.collect(Collectors.toList());Transforming Items (Map to Names)
// Before
public static List<String> extractNames(List<Product> products) {
List<String> names = new ArrayList<>();
for (Product p : products) {
names.add(p.getName());
}
return names;
}
// After
List<String> names = products.stream()
.map(Product::getName)
.collect(Collectors.toList());Sorting Products by Price
// Before
Collections.sort(products, new Comparator<Product>() {
public int compare(Product p1, Product p2) {
return Double.compare(p1.getPrice(), p2.getPrice());
}
});
// After
List<Product> sorted = products.stream()
.sorted(Comparator.comparing(Product::getPrice))
.collect(Collectors.toList());Finding the Most Expensive Product
// Before
public static Product findMax(List<Product> list) {
if (list.isEmpty()) return null;
Product max = list.get(0);
for (Product p : list) {
if (p.getPrice() > max.getPrice()) {
max = p;
}
}
return max;
}
// After
Optional<Product> max = products.stream()
.max(Comparator.comparing(Product::getPrice));Grouping Products by Name
// Before
public static Map<String, List<Product>> groupByName(List<Product> products) {
Map<String, List<Product>> map = new HashMap<>();
for (Product p : products) {
map.computeIfAbsent(p.getName(), k -> new ArrayList<>()).add(p);
}
return map;
}
// After
Map<String, List<Product>> grouped = products.stream()
.collect(Collectors.groupingBy(Product::getName));When to Still Use Utility-Style Generics
- To abstract logic that’s used in multiple places.
- To handle types outside of stream context (e.g., external APIs, data structures).
- When working with non-streamable inputs (arrays, trees, etc.).
- For backward compatibility or unit testing business logic.
- When using custom containers or libraries that aren’t stream-friendly.
- When needing custom reusable methods (especially if combining multiple behaviors).
- When working with legacy codebases or APIs that don’t support streams.
- For type-safe APIs or libraries where you expose generic behavior.








