2

I have piece of code I use to generate charts:

HashMap<String, List<Ticket>> openedTicketsPerTeam = getOpenedTicketsPerTeam();

How should I write signature of generic method to count length of list, every Map element? My idea was:

Map<String, Integer> getNumOfValuesPerKey(HashMap<String, List<? extends Object>> map) {...}

but after invocation there's conversion error:

HashMap<String, Integer> numOfTicketsPerTeam = getNumOfValuesPerKey(openedTicketsPerTeam );
1
  • 1
    can you post the error ? Commented Aug 7, 2012 at 6:29

3 Answers 3

1

Something like this (could be used for any key K and any list of Vs):

public static <K, V> Map<K, Integer> getNumOfValuesPerKey(Map<K, List<V>> map) {

    Map<K, Integer> count = new HashMap<K, Integer>();

    for (Entry<K, List<V>> entry : map.entrySet()) 
        count.put(entry.getKey(), entry.getValue().size());

    return count;
}

Example:

public static void main(String[] args) {

    HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();

    map.put("Hello", Arrays.asList(1,2,3));
    map.put("World", Arrays.asList(4,5));

    System.out.println(getNumOfValuesPerKey(map));
}

Output:

{Hello=3, World=2}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Map<String, Integer> numOfTicketsPerTeam = getNumOfValuesPerKey(openedTicketsPerTeam );

Your method (correctly) returns Map<String, Integer>, but you are assigning it to a HashMap<String, Integer> - there are multiple types of Map, the compiler has no way of knowing your implementation returns a HsshMap.

Note that you can, and should, simplify your method signature to:

Map<String, Integer> getNumOfValuesPerKey(Map<String, List<?>> map) {...}

Changes are to make the parameter a Map (not a HashMap) and List<?> (not List<? extends Object>, which is the same thing but more cruft)

Comments

0

No need to parameterize over the value type actually. The problem you had with Map<K, List<?>> is that non-wildcard generic parameters must match exactly. So in the second type parameter of Map, List<?> does not match List<Ticket>. The correct thing to do is to make that a wildcard also (with the added benefit of being able to work with implementing classes e.g. ArrayList as the parameter):

public static <K> Map<K, Integer> getNumOfValuesPerKey(Map<K, ? extends List<?>> map) {

    Map<K, Integer> count = new HashMap<K, Integer>();

    for (Map.Entry<K, ? extends List<?>> entry : map.entrySet()) 
        count.put(entry.getKey(), entry.getValue().size());

    return count;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.