1

I have a List of String L1

I have another List of String L2

I want to copy only those items from L1 to L2 which are not already contained in L2

I know it might be quite easy but I could not find an easy solution

Rahul Verma
  • 2,140
  • 3
  • 21
  • 31
  • Are the values in the List always unique? If yes, using a Set would be more appropriate. – Alexis C. Nov 28 '14 at 22:00
  • This question seems as a duplicate of http://stackoverflow.com/questions/5283047/intersection-and-union-of-arraylists-in-java. – wdk Nov 28 '14 at 22:33
  • You could remove the existing elements from the new list using removeAll and passing it the existing list, now the new list only contains the new items, you can now call addAll on the existing list passing it the new list... – MadProgrammer Nov 28 '14 at 22:36

3 Answers3

1

fill a set with the two lists, then convert the set back into a list (list2).

Set<String> set = new HashSet<String>(list2);
set.addAll(list1);
list2 = new ArrayList(set);
Kent
  • 189,393
  • 32
  • 233
  • 301
0

Take help form the below snippet. This will help.

        List<String> l1 = new ArrayList<String>();
        List<String> l2 = new ArrayList<String>();

        l1.add("A");
        l1.add("B");
        l1.add("C");

        l2.add("C");
        l2.add("D");
        l2.add("E");

        Set<String> s = new HashSet<String>();
        s.addAll(l1);
        s.addAll(l2);

        List<String> finalList = new ArrayList<String>();
        finalList.addAll(s);

        for (String str : finalList) {
            System.out.println(str);
        }
Ashu
  • 639
  • 6
  • 11
0

Something like

Set<String> stringSet = new HashSet<>(Arrays.asList(new String[]{"1","2","3"}));
stringSet.addAll(Arrays.asList(new String[]{"1","2","3","4"}));
List<String> finalList = new ArrayList<>(stringSet);
PDStat
  • 5,513
  • 10
  • 51
  • 86