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?

2
  • This could help stackoverflow.com/questions/2082449/… Commented Apr 15, 2013 at 11:36
  • You can make the code neater by reducing the number of lines required, but your not going to find anything faster than a O(n) iteration. Commented Apr 15, 2013 at 11:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 ;)
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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.