Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i query a List? Java

Tags:

java

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?

like image 796
TCM Avatar asked May 17 '10 11:05

TCM


2 Answers

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.

like image 112
RoToRa Avatar answered Oct 18 '22 00:10

RoToRa


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.

like image 22
14 revs, 12 users 16% Avatar answered Oct 17 '22 23:10

14 revs, 12 users 16%