I have two collections, collection 1 contains all items and collection 2 contains items selected. I need to create a new collection of only items that haven't been selected. What is the easiest method to create a new collection that only contains unselected items? A little snippet would be cool too.
The standard Collection classes have a "removeAll()" method which accepts another Collection as an argument; all the items in the first collection which appear in the second one are removed. So what you could do (if you need to preserve the full collection) is to construct a copy of it, and then use removeAll().
I tried to use the "Collection.removeAll()" method but both of my collections contain a collection of beans. How will collection2 know to remove the items that appear in collection1? I'm obviously missing something here. I'm fairly new to Java so excuse my lack of knowledge.
author and iconoclast
Well, let's see. How will removeAll() know to do this? Because that's what it does. I'm not sure how else to answer this tautological question. For the sake of discussion, here's a little example program. Is your situation substantially different from this?
This program prints "[a, d]".
Joined: Dec 16, 2003
I have two collections that each contain a collection ItemBeans. Each ItemBean has 2 getters/setters - ID(int) and Name(String).
As long as there's just one "copy" of a given ItemBean, this will just work, as given. If there are multiple copies -- i.e., two physically different ItemBeans that both represent "bean1", then for this to work, the ItemBean class has to properly override the equals() method, so that this method returns true when two ItemBeans are the same. Whenever you override equals(), you're supposed to do hashCode too. So...