如何合并arraylist中两个不同变量的两个对应值?

How to merge two corresponding values of two different variables in arraylist?

I want to merge two corresponding values of two different variables with comma separator in a row :

喜欢 车牌号(输出):MH 35353、AP 35989、NA 24455、DL 95405。

There is two different variables one is plate State and another is plate Number, I want to merge them together with their corresponding values like 1st values of plate State with 1st value of plate Number after that comma then so on..

我试过这个代码片段,但没有成功:

ArrayList<String> 
        list1 = new ArrayList<String>(); 

        list1.add("MH"); 
        list1.add("AP");
        list1.add("NA ");  
        list1.add("DL"); 

ArrayList<String> 
        list2 = new ArrayList<String>(); 

        list2.add("35353"); 
        list2.add("35989");
        list2.add("24455");
        list2.add("95405");

list1.addAll(list2); 

来自ArrayList#addAll Javadoc

Appends all of the elements in the specified collection to the end of this list[...]

这不是您想要的,因为您实际上不想追加对象,您想要将第一个列表的字符串与第二个列表的字符串合并。所以从某种意义上说,不是合并列表而是合并列表中的对象(字符串)。

最简单(对初学者最友好)的解决方案是自己创建一个简单的辅助方法,它可以满足您的需要。

像这样:

public static void main(String[] args) {
    ArrayList<String> list1 = new ArrayList<String>();
    list1.add("MH");
    list1.add("AP");
    list1.add("NA");
    list1.add("DL");

    ArrayList<String> list2 = new ArrayList<String>();
    list2.add("35353");
    list2.add("35989");
    list2.add("24455");
    list2.add("95405");

    ArrayList<String> combined = combinePlateNumbers(list1, list2);
    System.out.println(combined);
}

private static ArrayList<String> combinePlateNumbers(List<String> list1, List<String> list2) {
    ArrayList<String> result = new ArrayList<>();

    if (list1.size() != list2.size()) {
        // lists don't have equal size, not compatible
        // your decision on how to handle this
        return result;
    }
    // iterate the list and combine the strings (added optional whitespace here)
    for (int i = 0; i < list1.size(); i++) {
        result.add(list1.get(i).concat(" ").concat(list2.get(i)));
    }
    return result;
}

输出:

[MH 35353, AP 35989, NA 24455, DL 95405]

使用这个:

 ArrayList<String> 
            list1 = new ArrayList<String>(); 
    
            list1.add("MH"); 
            list1.add("AP");
            list1.add("NA ");  
            list1.add("DL"); 
    
    ArrayList<String> 
            list2 = new ArrayList<String>(); 
    
            list2.add("35353"); 
            list2.add("35989");
            list2.add("24455");
            list2.add("95405");
    
     Iterator iterable = list2.iterator();
            List<String> list3 =list1.stream()
                 .map(x->{
                    x= x+" "+((String) iterable.next());
                    return x;})
                 .collect(Collectors.toList());

     String output = String.join(", ", list3);
                   System.out.println(output);