java - 与 java 具有相同属性的过滤器列表(首选 groovy)
问题描述
我正在尝试过滤在 JAVA 中具有相同属性的对象列表。例如,我有这个 json
{
"id": 0,
"brand": "seat",
"brand_id": 1,
"model": "ibiza",
"year": 2010
},
{
"id": 1,
"brand": "seat",
"brand_id": 1,
"model": "leon",
"year": 2015
},
{
"id": 2,
"brand": "seat",
"brand_id": 1,
"model": "alhambra",
"year": 2008
},
{
"id": 3,
"brand": "ford",
"brand_id": 2,
"model": "focus",
"year": 2005
},
{
"id": 4,
"brand": "ford",
"brand_id": 2,
"model": "mondeo",
"year": 2018
},
{
"id": 5,
"brand": "ford",
"brand_id": 2,
"model": "fiesta",
"year": 2015
}
现在,如果我通过获取请求接收例如“brand_id”参数,我需要这样的东西。如果我收到 brand_id = 2 它显示:
{
"id": 3,
"brand": "ford",
"brand_id": 2,
"model": "focus",
"year": 2005
},
{
"id": 4,
"brand": "ford",
"brand_id": 2,
"model": "mondeo",
"year": 2018
},
{
"id": 5,
"brand": "ford",
"brand_id": 2,
"model": "fiesta",
"year": 2015
}
我怎样才能做到这一点?提前致谢
解决方案
我认为这将达到您的目的。
import java.util.stream.Collectors
import groovy.json.JsonSlurper
def json = '[{"id": 0, "brand": "seat", "brand_id": 1, "model": "ibiza", "year": 2010 }, { "id": 1, "brand": "seat", "brand_id": 1, "model": "leon", "year": 2015 }, { "id": 2, "brand": "seat", "brand_id": 1, "model": "alhambra", "year": 2008 }, { "id": 3, "brand": "ford", "brand_id": 2, "model": "focus", "year": 2005 }, { "id": 4, "brand": "ford", "brand_id": 2, "model": "mondeo", "year": 2018 }, { "id": 5, "brand": "ford", "brand_id": 2, "model": "fiesta", "year": 2015 }]'
def jsonSlurper = new JsonSlurper()
def jsonObj = jsonSlurper.parseText(json)
def carsWithId2 = ((List)jsonObj).findAll{car -> car.brand_id == 2}
print carsWithId2
这打印:
[[brand:ford, brand_id:2, id:3, model:focus, year:2005], [brand:ford, brand_id:2, id:4, model:mondeo, year:2018], [brand:ford, brand_id:2, id:5, model:fiesta, year:2015]]