简体   繁体   中英

Filtering Groovy map by a list

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'] 

Use subMap :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM