Groovy 过滤一组数据
具有一组表示具有以下属性的教室的数据Groovy 过滤一组数据,groovy,Groovy,具有一组表示具有以下属性的教室的数据 List classrooms = [ [code: "A", floor: 1, number: 20, airConditioned: true], [code: "A", floor: 1, number: 21, airConditioned: false], [code: "A", floor: 1, number: 22,, airConditioned: false], [code: "A", floor: 2,
List classrooms = [
[code: "A", floor: 1, number: 20, airConditioned: true],
[code: "A", floor: 1, number: 21, airConditioned: false],
[code: "A", floor: 1, number: 22,, airConditioned: false],
[code: "A", floor: 2, number: 20, airConditioned: false],
[code: "B", floor: 1, number: 21, airConditioned: false],
[code: "B", floor: 2, number: 30, airConditioned: false],
[code: "C", floor: 1, number: 40, airConditioned: true]
]
我需要通过代码、地板和空调进行过滤,例如,它们中的每一个都是可能为空的值列表
List codes = ["A", "C"]
List floors = [1]
List airConditioned = [true, false]
现在我正在尝试以下方法
List filter(List<Integer> floorList, List<String> codeList, List<Boolean> airConditionedList) {
List classrooms = getClassrooms()
List classroomList = []
classrooms.each { c ->
if (c.floor in floorList && c.code in codeList && c.airConditioned in airConditionedList) {
classroomList << c
}
}
classroomList
}
列表过滤器(列表floorList、列表codeList、列表airConditionedList){
列出教室=GetQuestions()
List classroomList=[]
教室.each{c->
if(地板列表中的c.地板和代码列表中的c.代码和空调列表中的c.空调){
classroomList您可以将您的筛选方法更改为:
List filter(List<Integer> floorList, List<String> codeList, List<Boolean> airConditionedList) {
classrooms.findAll { it.floor in floorList }
.findAll { it.code in codeList }
.findAll { it.airConditioned in airConditionedList }
}
列表过滤器(列表floorList、列表codeList、列表airConditionedList){
教室.findAll{it.floor in floorList}
.findAll{it.code在代码列表中}
.findAll{it.airrecated in airrecated list}
}
因此,您可以将以下内容添加到默认空列表中,以包含所有可能性:
List filter(List<Integer> floorList, List<String> codeList, List<Boolean> airConditionedList) {
// Make defaults for empty lists
(floorList, codeList, airConditionedList) = [
floor:floorList,
code:codeList,
airConditioned:airConditionedList
].collect { prop, list ->
list ?: classrooms[prop].unique()
}
classrooms.findAll { it.floor in floorList }
.findAll { it.code in codeList }
.findAll { it.airConditioned in airConditionedList }
}
列表过滤器(列表floorList、列表codeList、列表airConditionedList){
//为空列表设置默认值
(楼层列表、代码列表、空调列表)=[
楼层:楼层列表,
代码:代码列表,
空调:空调列表
].收集{prop,list->
列表?:教室[prop].unique()
}
教室.findAll{it.floor in floorList}
.findAll{it.code在代码列表中}
.findAll{it.airrecated in airrecated list}
}
感谢您的回答。经过一些测试后,我发现了一个问题。如果一些输入值为空,我会得到一个空列表作为响应。是的,因为您告诉它通过传递一个空列表来删除它们…一秒钟后,我将尝试提出一个基于默认值的解决方案