search object within java collection
first, I don't know if I'm organizing my data efficiently, the idea is that I have pairs of key/value.
public static class Freq implements Comparable {
String term;
double frequency;
public Freq( String term, double frequency ) {
this.term = term;
开发者_开发百科 this.frequency = frequency;
}
public int compareTo(Object o) {
if(this.frequency == ((Freq) o).frequency)
return 0;
else if(this.frequency > ((Freq) o).frequency)
return 1;
else
return -1;
}
Now, I'm storing such objects within a collection: List<Freq> bla = new ArrayList<Freq>()
as well as sorting it.
I'm interested to search for specific objects e.g. Freq.name = 'Bar'
from the collection, which is sorted. How would I do that? Or I have to iterate the whole collection.
or is there other more efficient ways to do this?
You should use an associated collection such as a TreeMap
, which keeps its elements sorted automatically. If you want to search sometimes based on name and sometimes on frequency, you can keep your elements in two maps at the same time, and use the suitable one for lookup.
Or if for some reason you want to stick with a sorted List, you can use Collections.binarySearch()
to find elements in it.
You can use JFilter http://code.google.com/p/jfilter/
JFilter is a simple and high performance open source library to query collection of Java beans.
Key features
- Support of collection (java.util.Collection, java.util.Map and Array) properties.
- Support of collection inside collection of any depth.
- Support of inner queries.
- Support of parameterized queries.
- Can filter 1 million records in few 100 ms.
- Filter ( query) is given in simple json format, it is like Mangodb queries. Following are some examples.
- { "id":{"$le":"10"}
- where object id property is less than equals to 10.
- { "id": {"$in":["0", "100"]}}
- where object id property is 0 or 100.
- {"lineItems":{"lineAmount":"1"}}
- where lineItems collection property of parameterized type has lineAmount equals to 1.
- { "$and":[{"id": "0"}, {"billingAddress":{"city":"DEL"}}]}
- where id property is 0 and billingAddress.city property is DEL.
- {"lineItems":{"taxes":{ "key":{"code":"GST"}, "value":{"$gt": "1.01"}}}} where lineItems collection property of parameterized type which has taxes map type property of parameteriszed type has code equals to GST value greater than 1.01.
- {'$or':[{'code':'10'},{'skus': {'$and':[{'price':{'$in':['20', '40']}}, {'code':'RedApple'}]}}]}
- Select all products where product code is 10 or sku price in 20 and 40 and sku code is "RedApple".
精彩评论