Kubekk
Kubekk

Reputation: 133

Generic method with map java

Let's say I have Employee class:

class Employee {
private String name;
private int salary;
// ...
}

I declared and initialized List of Employee employee. After it I created the map as u can see bellow:

 Map<String, List<Employee>> m = employee.stream().collect(Collectors.groupingBy(Employee::getName));

The question is, how to make a generic method which will be printing this map on the screen? I am stuck here, cause I have no idea, what to do with this List.

Was thinking about something like this:

public static <K, V> void showVal(Map<K,  List<V>> m) { 
    m.forEach((k, v) -> System.out.println("Key (name): " + k + " Salary: " + v) ); 
}

The above code gives me just references to employees, how to get a salary using the List in this generic method?

Upvotes: 0

Views: 202

Answers (1)

randers
randers

Reputation: 5146

You can use bounded generics. That way you can ensure that the values of the map are always some collection of instances of Employee:

private static <K, V extends Collection<? extends Employee>> void print(Map<K, V> map) {
    map.forEach((name, employees) -> {
        int sum = employees.stream()
                .mapToInt(Employee::getSalary)
                .sum();
        System.out.println("Employee: " + name + " with salary " + sum);
    });
}

Also see the official Oracle documentation: Generic Methods and Bounded Type Parameters

Upvotes: 1

Related Questions