views:

324

answers:

6

Is there any way to perform SQL Like Queries or Filtering on Java Data Structures?

I want to filter objects in an ArrayList and a HashMap by fields of the objects contained within.

+2  A: 

Yes and no.

No, not with a SQL like syntax.

Yes, with a filter functor. In particular, look at the Apache Commons Collections, CollectionsUtils.filter() function, which applies a Predicate object to a Collection.

You write the Predicate, the Apache classes take care of the rest.

tpdi
+3  A: 

There's not a standard SQL-like language, but the apache commons collections has a filter method that will do what you want. Not too hard to roll your own,

public <T> Collection<T> filter (Collection<T> c, Condition<T> condition) {
  ArrayList<T> list = new ArrayList<T>():
  for (T t: c){ 
        if (condition.isSatisfied(t)) { list.add(t); } 
  } 
  return list;
 }

public interface Condition<T> {
   public boolean isSatisfied(T t);
 }
Steve B.
+1  A: 

There are a number of solution for doing that that leverage XPath or XQuery. For starters take a look at Jaxen.

raiglstorfer
+2  A: 

The canonical way is to just iterate over the data structure and insert the objects you want into a new one. Unfortunately, Java has no list comprehensions or first-class functions. But we can simulate them using a library like Functional Java:

import fj.F;
import fj.data.List;
import static fj.data.List.list;
import static fj.pre.Show.listShow;
import static fj.pre.Show.stringShow;

List<String> myList = list("one", "two", "three").filter(
  new F<String, Boolean>() {
    public Boolean f(String s) {
      return s.contains("e");
    }
  });

listShow(stringShow).print(myList);

That will print ["one", "three"] to standard output.

Apocalisp
+5  A: 

You might like Quaere, which is a fairly rich query language for java object graphs:

Integer[] numbers={5, 4, 1, 3, 9, 8, 7, 2, 0};
Iterable<Integer> lowNumbers=
    from("n").in(numbers).
    where(lt("n",5).
    select("n");
Chris May
A: 

One rather extreme solution might be to use an ORM of some sort to map your Java objects into an actual SQL database, then use actual SQL or a SQL-like language like Hibernate's HQL to query your objects precisely how you'd like.

Of course, I'd only seriously consider that if I were actually planning to persist the objects in the database anyway, since otherwise it's overkill.

CaptainAwesomePants