java - Get a ArrayList containing the union of two different sized arraylist of some object type -
i have bean class containing 2 variables title , id.
public class bean(){ private string title; private string id; } i have 2 arraylists of type bean - arraylist firstlist , arraylist secondlist. both have different number of bean elements in them i.e. size 2 arraylist different , can huge in size. of bean elements present in them may contain same ids.
now have different bean class mainbean containing 3 variables
public class mainbean(){ private string firsttitle; private string secondtitle; private string id; } i need create new arraylist of type mainbean based on values above 2 arraylist - arraylist finallist.
while comparing above 2 arraylist (firstlist , secondlist), following needs kept in mind -
1) first condition - if same id present in both lists, new arraylist finallist have id populated , firsttitle firstlist , secondtitle secondlist.
2) if id firstlist not present in secondlist, finallist have id , firsttitle firstlist while secondtitle null.
3) if id secondlist not present in firstlist, finallist have id , secondtitle secondlist while firsttitle null.
please me form such finallist arraylist.
an idea use mergesort's merge procedure. so, first sort both lists, combine them 1 using conditions you've specified. code after sorting (more or less):
i = 0; j = 0; while (i < m && j < n) { bean b1 = firstlist.get(i); bean b2 = secondlist.get(j); int id1 = b1.getid(); int id2 = b2.getid(); if (id1 < id2) { // id2 bigger, firstlist, increment finallist.add(new mainbean(id1,b1.gettitle(),null); i++; } else if (id1 > id2) { // id1 bigger, secondlist, increment j finallist.add(new mainbean(id2,null,b2.gettitle())); j++; } else { // both same, both, increment both finallist.add(new mainbean(id1,b1.gettitle(),b2.gettitle())); i++; j++; } } while (i < m) { // take rest of firstlist bean b = firstlist.get(i); finallist.add(new mainbean(b.getid(),b.gettitle(),null)); i++; } while (j < n) { // take rest of secondlist bean b = secondlist.get(j); finallist.add(new mainbean(b.getid(),null,b.gettitle())); j++; } note:
- m = firstlist.length();
- n = secondlist.length();
- i assume finallist has been initialized before doing procedure
Comments
Post a Comment