Using generic keys for methods that return hashmaps

I have a function that takes a map where the keys can be of several types and the values ​​are always integers. I need to perform operations on values ​​that ignore keys and return a map at the end.

public Map<Sometype, Integer> doSomething(Map<Sometype, Integer> map, Integer total) {
    Map<Sometype, Integer> result = new HashMap<Sometype, Integer>();

    for (Sometype key :  map.keySet()) {
        result.put(key, map.get(key) * 2);
    }

    return result;
}

      

Map keys can be whole, logical, and enumerable. Is there a way to apply generics so that I can use this method with any type of card?

+3


source to share


1 answer


Yes. You can make your method generic to Sometype

.

public <Sometype> Map<Sometype, Integer> doSomething(
        Map<Sometype, Integer> map, Integer total) {
    Map<Sometype, Integer> result = new HashMap<Sometype, Integer>();
    for (Sometype key : map.keySet()) {
        result.put(key, map.get(key) * 2);
    }
    return result;
}

      



This can also be written as

public <T> Map<T, Integer> doSomething(Map<T, Integer> map, Integer total) {
    Map<T, Integer> result = new HashMap<T, Integer>();
    for (T key : map.keySet()) {
        result.put(key, map.get(key) * 2);
    }
    return result;
}

      

0


source







All Articles