过滤一组数据

时间:2016-07-03 20:41:02

标签: 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, 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
}

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您可以将filter方法改为:

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 }
}

因此,您可以将以下内容添加到默认空列表中以包含所有可能性:

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 }
}
相关问题