简体   繁体   中英

How to concat two list in java?

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?

Update

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;
}

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));
    }
}

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

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)

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));
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM