I have to remove duplicated objects in a List. It is a List from the object Blog that looks like this:
public class Blog {
private String title;
priv
If your Blog
class has an appropriate equals()
method defined on it, the simplest way is just to create a Set
out of your list, which will automatically remove duplicates:
List blogList = ...; // your initial list
Set noDups = new HashSet(blogList)
The chances are this will work transparently with the rest of your code - if you're just iterating over the contents, for example, then any instance of Collection
is as good as another. (If iteration order matters, then you may prefer a LinkedHashSet
instead, which will preserve the original ordering of the list).
If you really need the result to be a List
then keeping with the straightforward approach, you can just convert it straight back again by wrapping in an ArrayList
(or similar). If your collections are relatively small (less than a thousand elements, say) then the apparent inefficiencies of this approach are likely to be immaterial.