Forum Discussion

_lauren11's avatar
_lauren11
Occasional Contributor
4 years ago

how to use map in groovy

 i get response fron jdbc in the form of list 1:  [name., type, color, size, occassion]

and another response in the form of list 2: [saree, long, black, 5 inch, party]

 

now i want to combine list 1 and list 2 in the form of key value pair. such as [name: saree, type: long, color:black, size: 5 inch, occassion:party]

also, elements in list 1 and list 2 can vary. Sometimes, there can be more elements and sometimes less, depending upon the data in database. 

How to make dynamic groovy to achieve this .

thanks in advance

HimanshuTayal sir.

7 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3
    May be there can different solution if you can show the response data instead of list.
    • _lauren11's avatar
      _lauren11
      Occasional Contributor

      def nDB= nameDB.toString()

      when i print nDB, it displays:-      Wed Apr 29 17:27:01 IST 2020:INFO:[Code, Pattern, Size, Color, Suitable For, Dress Length, Brand, Fabric]

       

      def vDB= valueDB.toString()

      when i print vDB, it displays:-- Wed Apr 29 17:27:01 IST 2020:INFO:[W34, Self Design, M, Black, Girls, 140 cm, Hawai, Leon]

       

      no i want mapping as :- [code:W34, Pattern:Self Design, ....], hope this makes my question clear.

      I mean, to use nDB and vDB to generate key value

      nmrao sir

      • nmrao's avatar
        nmrao
        Champion Level 3
        what does it show for below statement

        log.info nameDB.metaClass
  • _lauren11 :

     

    What you can do is implement logic as below:

    1. validate that both array size is same

    2. loop through your 1st DB list, then iterate value 1 by one by index

    3. then insert it into HashMap

     

    def list1 = db1Array
    def list2 = db2Array
    
    def l1size = db1Array.size()
    def l2size = db2Array.size()
    //HashMap declaration
    HashMap<String, Object> hm = new HashMap<String, Object>();
    
    if(l1size ==l2size ){
         for(int i = 0 ; i< l1size ; i++)          
              hm.put(list1[i],list2[i]);
         }
    }
    log.info "This is HashMap > "+hm

    Hope it will help

    • _lauren11's avatar
      _lauren11
      Occasional Contributor

      This is a really good approach sir, but i think..the response from jdbc is not in the form of array..and beacuse of which, when i am finding out the size of both list1 and list2, it is varying. 

      list1.size()=153

      list2.size()=120

      and when i tried to convert them in list...and then when i tried to find it's size.. it returns 1. 

       

      • HimanshuTayal's avatar
        HimanshuTayal
        Community Hero

        what your list 1 and list 2 contains?

         

        could you send the response here or send the dummy response of both the lists?