首页 > 解决方案 > 如何合并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); 

标签: javaarraysarraylistcollections

解决方案


ArrayList#addAll Javadoc

将指定集合中的所有元素附加到此列表的末尾[...]

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

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

像这样的东西:

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]

推荐阅读