简体   繁体   中英

Java: Obtain the Subset of an Array that meet a criteria

I have an an array of arrays. float[][] Test

For example

  {  {433801.000f,335601.000f,5},
     {433821.000f,335631.000f,5},
     {433811.000f,335671.000f,5}  };

How can I get the subset of this array (or array of arrays), where the values meet a criteria.

For example where Test[i][0] > 40000 and Test[i][1] + Test[i][2] < 350000

I can obviously iterate through the list. But this will be very slow when the array is of huge magnitude.

How would I do this in a vectorised manner.

Im also using JavaME if this causes any limitations. But a JavaSE Solution would be great insight too and hopefully work in JavaME.

There's no way to do it without iterating unless you store more information about the data.

I would suggest that in addition to storing the full data, for every new record, you test it with your condition and if it's true, save the item reference in another array (well, Vector is better for both of these unless storage is really tight).

Then when you want all the items matching the condition, just look up all the references in the second "array". This is roughly how some database queries are optimised. The lookup cost is reduced at the expense of higher insertion and storage cost.

I think iterating over the entire array and testing those conditions is as fast as any other way. The upside is that it's very simple to implement. How big do you expect that array to be ? If, in the worst case, it'll have just a few thousand rows, you'll be ok :) .

The only way to avoid a linear scan is to store your data in a sorted manner. Using some kind of tree structure is probably the way forward for quick look up. This means not storing your data in arrays of arrays, which may violate your memory requirements, but that is the tradeoff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM