Querying Java Data Structures

Is there a way to run SQL Like Queries or Filtering on Java Data Structures?

I want to filter objects in ArrayList and HashMap by fields of objects contained inside.

+3
source share
6 answers

You might like Quaere , which is a fairly rich query language for graphing Java objects:

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

There is no standard SQL-like language, but collection collections apache has a filter that will do what you want. It's not too hard to roll on 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);
 }
+4

.

, SQL.

, . , Apache Commons Collections, CollectionsUtils.filter(), Predicate .

Predicate, Apache .

+3

- . , Java . , 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);

["one", "three"] .

+3

, XPath XQuery. Jaxen.

+1

One very extreme solution would be to use some kind of ORM to map your Java objects into the actual SQL database, and then use the actual SQL or a similar SQL language like Hibernate HQL to query your objects exactly as you would like .

Of course, I would only seriously think that if I really planned to permanently store objects in the database, otherwise it would be unnecessary.

0
source

Source: https://habr.com/ru/post/1706219/


All Articles