Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Grails 如何有条件地设置hashmap key:value对中的值?_Grails_Hashmap - Fatal编程技术网

Grails 如何有条件地设置hashmap key:value对中的值?

Grails 如何有条件地设置hashmap key:value对中的值?,grails,hashmap,Grails,Hashmap,我正在使用grails。 我想有条件地设置map中的值。 例如: 输出我想要的 像这样的 提前感谢。您正在使用groovy,所有这些都可以更优雅地完成: 你们一定是从什么地方得到这本书的 将此更改为: HashMap<String, String> mymap= new HashMap<String, String>(); if (author != null){ mymap['TITLE'] = book.title }else{

我正在使用grails。 我想有条件地设置map中的值。 例如:

输出我想要的

像这样的


提前感谢。

您正在使用groovy,所有这些都可以更优雅地完成:

你们一定是从什么地方得到这本书的

将此更改为:

HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }
致:

改用这个:

HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
 if (author != null){
    myList.add(book.title)
}else{
    myList.add('NA')    
}
map.put("TITLE",myList) ;
较短的变体:

HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )

不工作。我的列表仍然显示空值。工作非常出色但是,有没有办法避免列表中的空值?例如,我得到了以下输出:[title1,title2,NA,null,NA,null]我如何用'NA'替换'null'?听起来这些null可能不像实际的groovy null中那样是null,因为titleseach用于副作用。使用collect代替。
HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }
List titles=[]
books?.title?.each { title->
    titles<< (title?:'NA')
}
def mymap=['TITLE':titles]
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
 if (author != null){
    myList.add(book.title)
}else{
    myList.add('NA')    
}
map.put("TITLE",myList) ;
HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )