Get Common and Unique values between two strings:
String str1 = '1,2,3,4,5,6,7,8';
String str2 = '2,4,5,6,8,10,12';
List<string> theCommonNumbers=new List<string>();
List<string> theUniqueNumbers=new List<string>();
List<string> s1=str1.split(',');
List<string> s2=str2.split(',');
List<string> mergeList=new List<string>();
mergeList.addAll(s1);
mergeList.addAll(s2);
Integer l1=s1.size();
Integer l2=s2.size();
for(Integer i=0;i<=l1-1;i++){
for(Integer j=0;j<=l2-1;j++){
if( (s1[i] == s2[j])) {
theCommonNumbers.add(s1[i]);
break;
}
}
}
Integer i = 0, j = 0, k = 0;
while (i < l1 && j < l2) {
if (s1[i] < s2[j]) {
theUniqueNumbers.add(s1[i]);
i++;
k++;
}
else if (s2[j] < s1[i]) {
theUniqueNumbers.add(s2[j]);
k++;
j++;
}
else {
i++;
j++;
}
}
while (i < l1) {
theUniqueNumbers.add(s1[i]);
i++;
k++;
}
while (j < l2) {
theUniqueNumbers.add(s2[j]);
j++;
k++;
}
system.debug('theCommonNumbers'+theCommonNumbers);
system.debug('theUniqueNumbers'+theUniqueNumbers);
String str2 = '2,4,5,6,8,10,12';
List<string> theCommonNumbers=new List<string>();
List<string> theUniqueNumbers=new List<string>();
List<string> s1=str1.split(',');
List<string> s2=str2.split(',');
List<string> mergeList=new List<string>();
mergeList.addAll(s1);
mergeList.addAll(s2);
Integer l1=s1.size();
Integer l2=s2.size();
for(Integer i=0;i<=l1-1;i++){
for(Integer j=0;j<=l2-1;j++){
if( (s1[i] == s2[j])) {
theCommonNumbers.add(s1[i]);
break;
}
}
}
Integer i = 0, j = 0, k = 0;
while (i < l1 && j < l2) {
if (s1[i] < s2[j]) {
theUniqueNumbers.add(s1[i]);
i++;
k++;
}
else if (s2[j] < s1[i]) {
theUniqueNumbers.add(s2[j]);
k++;
j++;
}
else {
i++;
j++;
}
}
while (i < l1) {
theUniqueNumbers.add(s1[i]);
i++;
k++;
}
while (j < l2) {
theUniqueNumbers.add(s2[j]);
j++;
k++;
}
system.debug('theCommonNumbers'+theCommonNumbers);
system.debug('theUniqueNumbers'+theUniqueNumbers);
Comments
Post a Comment