Can I query a List?
Say I have
List<SomeObject> objList = new ArrayList<SomeObject>();
If SomeObject contains a field named id. Can we find it through some query like
objList.filter('id=2');
without looping through the list? If not, then why? This can be such a useful method and can be used as an alternative to 开发者_如何学Cwrite a tedious for loop.
Libraries with functional, well, functionality such as functionaljava provide such methods.
You'd need to use its own List
implementation which is incompatible to native Javas (Array)List
or convert between the two.
An Example:
import fj.data.Java
import fj.data.List
import fj.F
// Converting an ArrayList
fj.data.List<SomeObject> objList2 = Java.ArrayList_List().f(objList);
fj.data.List<SomeObject> filteredObjList = objList2.filter(new F<SomeObject, Boolean>() {
Boolean f(SomeObject c) { return c.id == 2; }
});
// Converting back to ArrayList
java.util.List<SomeObject> objList2 = Java.List_ArrayList().f(filteredObjList );
By using functionaljava's List
through out of your project you would avoid the converting.
Even if this was a supported feature of the language, then it would be Java that would need to do the iterating, so you're back at square one (in terms on time complexity).
What you're looking for is associative mapping. This can be achieved with HashMap. If you want to associate by more than one type of property for example id AND name, then you could make two HashMaps, one whose key is id and one whose key is name.
This of course doesn't scale very well if you want to query for many properties, so the next step would be using an Object oriented database such as Hibernate which will allow you to query the database for objects exactly as in your example.
short: no, you can't
long: you can write own data structure and hash/index fields of object for some more efficient search. but this is not a list, more HashMap
or so.
Probably this will help someone,
http://code.google.com/p/joquery/
this library supports following code structure,
Filter<Dto> query = CQ.<Dto>filter(testList)
.where()
.property("id").eq().value(1);
Collection<Dto> filtered = query.list();
If you want something like linq for java, check out quaere
Edit: At this point, quaere looks like it is unmaintained. With Java 7 being EOL, you should be on Java 8 whose Stream API should get you most of the way there when compared to Linq's dot syntax. See this page for some examples.
Here How do you query object collections in Java (Criteria/SQL-like)? you can see some nice option/ I've sopped on this one actually.
精彩评论