I have to remove elements from ArrayList
, but I have not gone through it. Elements which I have to remove are also available in ArrayList
. In short, I have to remove one Array List from another Array List. e.g. Suppose
ArrayList<String> arr1= new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr2.add("2");
arr2.add("4");
Now, I have to remove elements which are in arr2 from arr1. So, that I have final answer as 1 and 3. What needs to be done?
To remove duplicate of one from other use this
Ok to make things clear:
if your list is composed of basic elements such as String etc all you need to do is use
assuming that isnt the case meaning you created a list from custum objects - the above method wont work, that is due to the nature of the item comparison. it uses the object.equals method which by default checks if this is the same instance of the object in the other list (which it probably isnt)
so in order for this to work you need to overwrite the custom object equals method.
example - test if 2 contacts are the same based on phone number:
now if you use
it will compare the items based on the desired attribute (in the example based on phone number) and will work as planned.
Read Remove Common Elements in Two Lists Java
Use below code
Or can be done by
After SO comments
I used the following code
and getting output as
So what is not working at your side?
Read more about How do you remove the overlapping contents of one List from another List?
You can use removeAll() function
Take new
arr
as final sorted array