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');
wihout looping through the list? If not, then why? This can be so useful method and used as an alternative to write 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With