2

What is the fastest way to get the selected objects from an array?

MyObject[] objects = new MyObject[]{new MyObject(true), new MyObject(false)};
MyObject[] selectedObjects = ???

Is there a faster way than:

ArrayList<MyObject> selObjectsList = new ArrayList<MyObject>();
for(MyObject obj : objects){
   if(obj.isSelected()){
       selObjectsList.add(obj);
   }
}
selectedObjects = selObjectsList.toArray(new MyObject[0]);

This are many lines for a simple operation, is there a shorter operation to do the same?

Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
Jetse
  • 1,706
  • 2
  • 16
  • 22

3 Answers3

3

With the standard libraries, there is no (fundamentaly) neater way to do it. But there are numerous third-party libraries that have filter or predicate support. Google Collections comes to mind. And I have also heard good things about LambdaJ. Hopefully, things will improve with Java 8!

With LambdaJ it could look something like this:

select(myList, having(on(MyObject.class).isSelected()));

Edit I interpreted "fastest" as shortest number of lines. If it was performance you was thinking of, this answer might not be appropriate.

NilsH
  • 13,705
  • 4
  • 41
  • 59
  • 1
    Im using this a multiple times in my code, but it is always executed only once, so the big O doesn't matter. The code becomes much more readable now ;) – Jetse Apr 15 '13 at 12:00
0

Unfortunately, no. If you are using an ArrayList, which is a linear list, then your are effectively forcing a linear search.

If you want to improve lookup, then you can use something like a Map that will allow quicker lookups, but you will have to use an intelligent method for setting the keys. For instance, if you were lookup up orders, you might use the order number as the key.

CodeChimp
  • 8,016
  • 5
  • 41
  • 79
0

Use a Map.

  Map<Boolean, List<MyObject>> someMap;

Then you can do the following to retrieve the List of 'MyObjects' that are selected.

  someMap.get(true); 

And to populate...

  someMap.put(myObjectInstance.isSelected(), myObjectInstance);
Bob Flannigon
  • 1,204
  • 9
  • 8