Search code examples
groovykeyvaluepair

Display multiple values of a key


I have a key and multiple value pairs.how to display the values.

def empData=[[dob:01/10/1970, qualifications:[java:[5/6, 7]],name:'T1'],
             [dob:01/02/1981,qualification:[DBA:['Professional','Specialist']],name:'T2']]

empData.eachWithIndex{item,idx->
    println("emp dob:"+item.dob);
    String[] qualifications = item.qualifications.get("java");
    println("qualification is:"+qualifications[0]);
    println("qualification is:"+qualifications[1]);
    println("emp name is:"+name);
}

I want the output to be as below:

// first record
   01/10/1970
   5/6
   7
   T1

   second record
   01/02/1981
   Professional
   Specialist
   T2


  Throws an error null pointer exception.

Solution

  • As mentioned in the other answers, there are issues with your code which seem to indicate that it would be useful for you to spend a little more time with the groovy documentation. With that being said, it is sometimes useful with a working example.

    The below code:

    def employees=[[dob:            '01/10/1970', 
                    name:           'T1',
                    qualifications: [java:   ['5 years', '15 projects'],
                                     python: ['Senior Developer']]],
                   [dob:            '01/02/1981', 
                    name:           'T2',
                    qualifications: [dba:  ['Professional','Specialist']]]]
    
    employees.indexed().each { idx, employee ->
      println "       Employee: ${employee.name}"
      println "            dob: ${employee.dob}"
    
      employee.qualifications.each { field, qualifications -> 
        println "                 ${field} - ${qualifications.join(', ')}"
      }
    }
    

    prints out:

           Employee: T1
                dob: 01/10/1970
                     java - 5 years, 15 projects
                     python - Senior Developer
           Employee: T2
                dob: 01/02/1981
                     dba - Professional, Specialist
    

    when run. The formatting is not exactly what you specified, but at least you can get a feel for how nested iteration can be done. The data in your example is broken to a point where it is hard to know exactly what you intended. I formatted the data in a way I assume is in line with your intent.