0

I have 3 list of data and I need to merge and maintain the order of insertion and there should not be any duplicates,

 For Eg:
 List l1=new LinkedList<>();
    l1.add("b");
    l1.add("a");
    l1.add("o");
    List l2=new LinkedList<>();
    l2.add("m");
    l2.add("n");
    List l3=new LinkedList<>();
    l3.add("m");
    l3.add("n");
    l3.add("o");
After merging the value should be
First Merging  b a o m n      
Second merging b a m n o

The input won't get modify in its order. If the value exist in first and it should be on first only.

EDIT to include OP's additional requirement:

the record in first should not move to middle. In case l3.add("b"); at first then the record should give [a, m, b, n, o] but we have b in first list(l1) as well and it should be b,a,m,n,o.

drognisep
  • 579
  • 1
  • 7
  • 16
user3428736
  • 864
  • 2
  • 13
  • 33
  • 2
    Possible duplicate of [LinkedHashSet - insertion order and duplicates - keep newest "on top"](http://stackoverflow.com/questions/36399845/linkedhashset-insertion-order-and-duplicates-keep-newest-on-top) – shmosel Jan 12 '17 at 02:32
  • `If the value exist in first and it should be on first only.` Your final list should be `b a o m n` i guess. – Abdullah Khan Jan 12 '17 at 05:46

2 Answers2

2
List<String> result = new LinkedList<>();
result.addAll(l1);
result.removeAll(l2);
result.addAll(l2);
result.removeAll(l3);
result.addAll(l3);
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

This will get the result you're looking for. The for/each loops through each element in other, adding them to base, but removing the existing element if it's there. This will work for your strings because they're being pulled from the string pool in this example. You'll have to do some more comparisons otherwise.

public List<String> merge(List<String> base, List<String> other) {
    for(String s : other) {
        if(base.indexOf(s) != 0)
            base.remove(s);
        else continue;
        base.add(s);
    }
    return base;
}

Edited for additional requirement that first element isn't replaced.

drognisep
  • 579
  • 1
  • 7
  • 16
  • it will work for the above example but there is one more condition the record in first should not move to middle. In case l3.add("b"); at first then the record should give [a, m, b, n, o] but we have b in first list(l1) as well and it should be b,a,m,n,o. – user3428736 Jan 12 '17 at 06:47
  • @user3428736 Edited for your additional requirement that the first element isn't replaced, does that answer your question? – drognisep Jan 13 '17 at 13:48