简体   繁体   English

如何在Java中合并两个列表?

[英]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. 我想将列表1中的空值替换为从列表2的同一列中核心扩展它们的值,结果将存储在列表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. 使用for循环。 Within the loop, use an if statement. 在循环中,使用if语句。 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) 由于您需要访问每个元素,因此请勿对每个i使用list.get(i),因为这将使复杂度为O(n ^ 2)而不是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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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