Search code examples
listgrailsgroovycriteriahibernate-criteria

How to get the value of one element in a List in groovy/grails


After do a createCriteria query, I have a object list of only 1 item with 7 strings inside. That I want to do is get only one of this seven elements??

List<Object> result - com.test.MyService.getConfig(String, String, String, String, String, String, String)

This are the elements that I get in the list:

[name:John, surname:John city:Rome, car:BMW, country:Italy, day:Monday, color:Red,]

I want access for example only to get the string 'country' to can return it in a method:

I'm trying to do this:

result.get(4)

And I'm gettin this error:

java.lang.IndexOutOfBoundsException: Index: 4, Size: 1

Solution

  • Try

    def oneObject = YourDomainClass.createCriteria().get{
         //add your criteria if any
    }
    return oneObject.country
    

    You get java.lang.IndexOutOfBoundsException: Index: 4, Size: 1 because when you execute YourDomainClass.createCriteria().list{} you get a list of YourDomainClass objects (which has only one object). So if you want to use YourDomainClass.createCriteria().list{} you should execute:

    def objects = YourDomainClass.createCriteria().list{}
    if(objects) //check if any object is in list
        return objects[0].country