RoyalTiger
RoyalTiger

Reputation: 541

Can I convert a Map<String, List<Integer>> into a MultiValueMap<String, Integer>

I am trying to convert a map into multivalue map, but I am getting the below compilation exception:

Wrong 1st argument type. Found: java.util.Map<java.lang.String,java.util.List<java.lang.String>>, required: org.springframework.util.MultiValueMap<java.lang.String,java.lang.String> less... Inspection info:

Here is the structure: Map<String, List<String>> tradersTradeMap - > MultiValueMap<String, String>tradersTradeMap

class Trade {

  public String getTraderNameAfterProcesing (MultiValueMap<String, String> 
      tradersTradeMap){
      ..... // SOme code goes here
   }

}

class Customer {

private Trade trade;

public String Method1(){
   Map<String, List<String>> traderTradeMap = new HashMap<>();
   traderTradeMap.put("TraderA", Arrays.asList("SPOT","BLOCK","FORWARD"));
   traderTradeMap.put("TraderB", Arrays.asList("SPOT","BLOCK"));

   trade = new Trade();
   trade.getTraderNameAfterProcesing(traderTradeMap); // This line is giving exception 

}

}

Is there any simple way to do it?

Upvotes: 8

Views: 31199

Answers (2)

Bruno Marques
Bruno Marques

Reputation: 91

Yes, Spring provides a handy wrapper in the form of CollectionUtils.toMultiValueMap(), which preserves the original Map used.

Upvotes: 9

Powerlord
Powerlord

Reputation: 88796

If you don't care about which MultiValueMap type you use, the easiest way to do it is to use LinkedMultiValueMap's copy constructor which takes a Map<K, List<V>>

One problem in your example is that you're trying to give the original map and the MultiValueMap the same variable name. So, if you instead did something like this:

MultiValueMap<String, String> TradersTradeMVMap = new LinkedMultiValueMap<>(TradersTradeMap);

Upvotes: 16

Related Questions