How do you query object collections in Java (Criteria/SQL-like)?

后端 未结 7 1432
醉话见心
醉话见心 2020-11-30 05:03

Suppose you have a collection of a few hundred in-memory objects and you need to query this List to return objects matching some SQL or Criteria like query. For example, you

7条回答
  •  生来不讨喜
    2020-11-30 05:25

    The Comparator option is not bad, especially if you use anonymous classes (so as not to create redundant classes in the project), but eventually when you look at the flow of comparisons, it's pretty much just like looping over the entire collection yourself, specifying exactly the conditions for matching items:

    if (Car car : cars) {
        if (1959 < car.getYear() && 1970 > car.getYear() &&
                car.getLicense().startsWith("AZ")) {
            result.add(car);
        }
    }
    

    Then there's the sorting... that might be a pain in the backside, but luckily there's class Collections and its sort methods, one of which receives a Comparator...

提交回复
热议问题