Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with Key as String and Value as List in Groovy

Tags:

map

groovy

Can anyone point me to an example of how to use a Map in Groovy which has a String as its key and a List as value?

like image 497
Sripaul Avatar asked Sep 02 '12 14:09

Sripaul


People also ask

How do I create a map object in Groovy?

We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line. Notice that the keys aren't surrounded by quotes, and by default, Groovy creates an instance of java.

How do I iterate a map in Groovy?

If you wanted to do it that way, iterate over map. keySet() and the rest will work as you expected. It should work if you use s. key & s.

How do you add a string value to a string map?

Maps are associative containers that store elements in a specific order. It stores elements in a combination of key values and mapped values. To insert the data in the map insert() function in the map is used.


1 Answers

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax   Map<String,List> map1  = new HashMap<>(); List list1 = new ArrayList(); list1.add("hello"); map1.put("abc", list1);  assert map1.get("abc") == list1;  // slightly less Java-esque  def map2  = new HashMap<String,List>() def list2 = new ArrayList() list2.add("hello") map2.put("abc", list2) assert map2.get("abc") == list2  // typical Groovy  def map3  = [:] def list3 = [] list3 << "hello" map3.'abc'= list3 assert map3.'abc' == list3 
like image 182
Michael Easter Avatar answered Sep 19 '22 03:09

Michael Easter