sumedha
sumedha

Reputation: 489

Java Generic Map with Generic Type as key/ values

I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it.

Below is the code that I have tried so far. This code as two methods: genericTest, where I am trying to implement a generic solution, and nonGenericTest, which is what I actually want to do with the generic solution but is implemented without using generics. Basically, the second method is the one which I want to convert to generics.

What am I doing wrong?

import java.util.Iterator;
import java.util.Map;

public class Test {
    //V cannot be resolve to a type
    public void genericTest(Map<String, V> params) {
    }

    public void nonGenericTest(Map<String, Object> params) {

        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key =  it.next();
            Object value = params.get(key);
            if(value instanceof String){
                String val1=(String) value;
                // do something 
            }else if(value instanceof Integer){
                Integer val1 = (Integer) value;
            } 
        }
    }
}

I am getting compiler error as shown in the code.

Upvotes: 0

Views: 11550

Answers (2)

Arefe
Arefe

Reputation: 12397

I would suggest to use it with the class definition like this:

public class SettingsClient<T> extends TestWebserviceClient {

    private Map<String, List<T>> mapWithAllPojoLists = new HashMap<>();

}

Inside the method, you can read/ write to the map like this:

   public List<Discount> getListOfDiscounts() {

        if (mapWithAllPojoLists.get("discount") != null) {
            return (List<Discount>) mapWithAllPojoLists.get("discount");
        }

        GetDiscountsResponse response = getGetDiscountsResponse();
        ArrayOfDiscount arrayOfDiscount = response.getGetDiscountsResult().getValue();

        List<Discount> discounts = arrayOfDiscount.getDiscount();

        if (discounts == null) {
            return new ArrayList<>();
        }

        mapWithAllPojoLists.put("discount", (List<T>) discounts);
        return discounts;
    }

Upvotes: 0

Makoto
Makoto

Reputation: 106390

You've got two options:

  • Introduce V as a type parameter to the class.

    public class Test<V>
    
  • Introduce V as a type parameter to that function.

    public <V> void genericTest(Map<String, V> params)
    

Upvotes: 8

Related Questions