按列表过滤Groovy地图 [英] Filtering Groovy map by a list

查看:52
本文介绍了按列表过滤Groovy地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在groovy中,有一种简单的方法可以通过列表过滤地图的索引.

In groovy is there a simple way to filter a map`s indexes by a list.

produce_map        = ["grapes":"fruit","apple":"fruit","tomato":"vegetable","peas:"vegetable"]
green_produce_list = ["grapes","apples",'peas']

<magic code>

//desired result
filterd_map = ['apple':'fruit','grapes':'fruit','peas':'vegetable'] 

推荐答案

使用

创建一个包含给定键的子映射.此方法类似于List.subList(),但使用键而不是索引范围.原始地图未更改.

Creates a sub-Map containing the given keys. This method is similar to List.subList() but uses keys rather than index ranges. The original map is unaltered.

def orig = [1:10, 2:20, 3:30, 4:40]
assert orig.subMap([1, 3] as int[]) == [1:10, 3:30]
assert orig.subMap([2, 4] as Integer[]) == [2:20, 4:40]
assert orig.size() == 4

这篇关于按列表过滤Groovy地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆