-2

I wanted from java pro out there the best way to remove items from list?

The scenario I have been working with is lets say I have list of object Balls and I want to remove all the balls that have color "RED"

Ball {
    private String Color;
}

The best way I can come up with is

Iterator<Balls> i = lst.iterator();
    while (i.hasNext()) {
      if     (i.next().getColor().equals("RED")) {
    i.remove();
  }

return lst;

I wanted to know if there is better/more concise way to do this, using Collections or any other library. Please keep in mind I am writing for Android so cannot use streams from Java 8 yet. I am using retrolambda however, but it still dose not support streams yet.

rage_against
  • 87
  • 10
  • There are a zillion ways to do this if you include being able to use arbitrary libraries. I don't know if retrolambda/etc includes `Collection#removeIf`. – Dave Newton Sep 21 '15 at 17:24
  • Just one question: why? What are you trying to achieve? Any particular reason for asking this? – async Sep 21 '15 at 17:40
  • @DaveNewton I didn't see any remove methods with Collections library, I have retrolambda added to my project. That is something I was looking for but didn't find it which lead to this question. I only found ways to use stream from java 8 but it is not supported by retrolambda. – rage_against Sep 22 '15 at 20:33

2 Answers2

1

There is no "better" way given your choice of data structure. You don't have any option but to iterate and remove the elements one by one. You may get some performance improvements in some situations if your list is sorted, but I wouldn't bother without knowing your constraints. Some API's may give you more concise ways of doing it (though I wouldn't bet on that - you're using Java after all), but fundamentally they still iterate the list.

You could try to use a dictionary (HashMap) if fast access is of critical importance to you, but really, why bother? If you want to optimize your code, you may be focusing on the wrong thing. If you want to improve it, making it more concise may not be the best idea, because it may lead to unreadable code.

async
  • 1,537
  • 11
  • 28
0

I went with using Iterable filter from guava library:

    final Iterable<Ball> filterRedBalls = Iterables.filter(Ball, 
        ball -> !(ball.getColor().equals("RED")));`

I think this gave a much cleaner and shorter code for the task. I haven't done any benchmarking to see if there was any performance improvement.

rage_against
  • 87
  • 10