mainstringargs
mainstringargs

Reputation: 14411

Querying Java Data Structures

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.

Upvotes: 3

Views: 2581

Answers (6)

Apocalisp
Apocalisp

Reputation: 35054

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.

Upvotes: 3

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38399

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.

Upvotes: 0

Chris May
Chris May

Reputation: 670

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");

Upvotes: 5

Steve B.
Steve B.

Reputation: 57333

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

Upvotes: 4

ra9r
ra9r

Reputation: 4738

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

Upvotes: 1

tpdi
tpdi

Reputation: 35171

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.

Upvotes: 3

Related Questions