0

I have two Custom Arraylist:

List<Item> before = new ArrayList<Item>();
List<ItemEx> after = new ArrayList<ItemEx>();

before.add(new Item(1L,"test1"));
before.add(new Item(2L,"test2"));
before.add(new Item(3L,"test3"));

after.add(new ItemEx(1L,"test4"));
after.add(new ItemEx(2L,"test5"));
after.add(new ItemEx(4L,"test6")); 
after.add(new ItemEx(5L,"test7")); 

I want to store the elements in the List<ItemEx> after and the element shoulds be after the removing of common element is {3L, 4L, 5L}.

5
  • 1
    add items from both list into HASHSET, after that you get only, 1L,2L,3L,4L,5Lin hashset Commented May 29, 2017 at 8:22
  • after.removeAll(before) works if you can somehow compare the objects correctly (maybe override .equals method). @DivyeshPatel how does this remove common elements from after list? Commented May 29, 2017 at 8:24
  • HASHSET allows only unique entry, so it store only unique data Commented May 29, 2017 at 8:26
  • @DivyeshPatel i want to remove the common elements. Commented May 29, 2017 at 8:47
  • @ShikhaRatra check my answer Commented May 29, 2017 at 9:02

3 Answers 3

2

FYI

List<Item> & List<ItemEx> should be SAME TYPE .

Logic

List<String> before = new ArrayList<String>();
List<String> after = new ArrayList<String>(); 
List<String> list_checking = new ArrayList<String>(before);
                            list_checking.addAll(after);
                            List<String> list_common = new ArrayList<String>(before);
                            list_common.retainAll(after);
                            list_checking.removeAll(list_common);
Sign up to request clarification or add additional context in comments.

1 Comment

my ArrayList is not of same type
0

Try this :

HashSet hs = new HashSet();
hs.addAll(before);
hs.addAll(after);
after.clear();
after.addAll(hs);

Now, in after list you get desire values.

Comments

0

Its simple. Take a copy of the existing one into a temporary Variable if you want for future use.

ArrayList temporiginalArrList=OriginalArrayList; //here 'T' can be a specific object to want to save

OriginalArrayList.removeAll(secondArrayList);

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.