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

后端 未结 7 1445
醉话见心
醉话见心 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:33

    yes, I know it's an old post, but technologies appear everyday and the answer will change in the time.

    I think this is a good problem to solve it with LambdaJ. You can find it here: http://code.google.com/p/lambdaj/

    Here you have an example:

    LOOK FOR ACTIVE CUSTOMERS // (Iterable version)

    List activeCustomers = new ArrayList();  
    for (Customer customer : customers) {  
      if (customer.isActive()) {  
        activeCusomers.add(customer);  
      }  
    }  
    

    LambdaJ version

    List activeCustomers = select(customers, 
                                            having(on(Customer.class).isActive()));  
    

    Of course, having this kind of beauty impacts in the performance (a little... an average of 2 times), but can you find a more readable code?

    It has many many features, another example could be sorting:

    Sort Iterative

    List sortedByAgePersons = new ArrayList(persons);
    Collections.sort(sortedByAgePersons, new Comparator() {
            public int compare(Person p1, Person p2) {
               return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
            }
    }); 
    

    Sort with lambda

    List sortedByAgePersons = sort(persons, on(Person.class).getAge()); 
    

    Update: after java 8 you can use out of the box lambda expressions, like:

    List activeCustomers = customers.stream()
                                              .filter(Customer::isActive)
                                              .collect(Collectors.toList());                                      
    

提交回复
热议问题