HYBR1D
HYBR1D

Reputation: 462

Java - How to pass a List type to a HashMap?

I'm trying to make a method public static Object getMostOccurringObject(List<?> list) which should return the most occurring object in the given list, or null if there are multiple objects with the highest occurrence.

In order to achieve this, I need to use a HashMap with the objects in list as key and the frequency of that object as value: HashMap<[type of list], Integer>.

This is what I've come up with:

public static <T> T getMostOccuringObject(List<T> list) {
    HashMap<T, Integer> map = new HashMap<>();
    for (T item : list) {
        if (map.containsKey(item)) {
            map.put(item, map.get(item) + 1);
        } else {
            map.put(item, 1);
        }
    }
    int max = Collections.max(map.values());
    if (Collections.frequency(map.values(), max) == 1) {
        for (T object : map.keySet()) {
            if (map.get(object).equals(max)) {
                return object;
            }
        }
    }
    return null;
}

But I'm not sure if this will do what I want. The code does compile. Could anyone confirm for me if this works, and if not, how I can make it work?

Upvotes: 0

Views: 92

Answers (2)

Pavan Kumar Mandala
Pavan Kumar Mandala

Reputation: 1

the following works for you. and also make sure parameters should have proper hashcode&equals method

public static <T> Object getMostOccuringObject(List<T> c) {
HashMap<T, Integer> frequency = new HashMap<>();
// rest of the code

}

refer: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html

Upvotes: 0

Jacob G.
Jacob G.

Reputation: 29700

By using a wildcard ? as the key to your Map, no elements will be able to be added; the Map#put method expects a capture type, and will not compile when you attempt to add any Object to it. Instead, you can use a generic:

public static <T> T getMostOccuringObject(List<T> c) {
    Map<T, Integer> frequency = new HashMap<>();
    // rest of the code
}

Upvotes: 3

Related Questions