Reputation: 149
I want to replace the null values in list 1 by the values that corespand them from the same column of list 2, the result will be stored in list 3.
List<Date> list1 = Arrays.asList(opDate1, null, opDate2, null, opDate3);
List<Date> list2 = Arrays.asList(date1, date2, date3, date4, date5);
result :
List<Date> list3 = Arrays.asList(opDate1, date2, opDate2, date4, opDate3);
How should I proceed?
My code :
public List<Date> concatList(List<Date> list1, List<Date> list2) {
List<Date> list3 = new ArrayList<Date>();
for(int i=0; i<list1.size();i++){
for(int j=0; i<list2.size();j++){
if(list1.get(i) == null)
list3.add(list2.get(j));
else
list3.add(list1.get(i));
}
}
return list3;
}
Upvotes: 0
Views: 1076
Reputation: 59
I think that it works
public List<Date> concatList(List<Date> list1, List<Date> list2) {
List<Date> list3 = new ArrayList<Date>();
/* here you will remove all null in your list*/
list1.removeIf(Objects::isNull);
list2.removeIf(Objects::isNull);
/* here you will add both list inside list3*/
list3.addAll(list1);
list3.addAll(list2);
}
Upvotes: 0
Reputation: 16
Try this
List<String> list3 = new ArrayList<>();
for (int i = 0;i <list1.size();i++) {
list3.add(list1.get(i) != null ? list1.get(i) : list2.get(i));
}
Upvotes: 0
Reputation: 386
List<String> list3 = new ArrayList<>();
ListIterator<String> iter1 = list1.listIterator();
ListIterator<String> iter2 = list2.listIterator();
while(iter1.hasNext()) {
String a = iter1.next();
String b = iter2.next();
if(a!=null) {
list3.add(a);
}
else{
list3.add(b);
}
}
Since you need to access each element, don't use list.get(i) for each i since that will give a complexity of O(n^2) rather than O(n)
Upvotes: 1
Reputation: 688
Try this
List<String> list3 = new ArrayList<>(list1.size());
for (int i=0;i<list1.size();i++) {
if (list1.get(i) == null) {
list3.add(i,list2.get(i));
} else {
list3.add(i,list1.get(i));
}
}
Upvotes: 2
Reputation: 433
Use a for loop. Within the loop, use an if statement. If the value at the specific point is null, replace it with the same location value from the other List
Upvotes: 1