java - 如何合并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);
解决方案
将指定集合中的所有元素附加到此列表的末尾[...]
这不是您想要的,因为您实际上不想附加对象,您想将第一个列表的字符串与第二个列表的字符串合并。所以从某种意义上说,不是合并列表而是合并列表中的对象(字符串)。
最简单(最适合初学者)的解决方案是自己创建一个简单的辅助方法,它可以满足您的需求。
像这样的东西:
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]
推荐阅读
- c++ - LNK1104:无法打开文件“opus.lib”
- reporting-services - SSRS 我有一个列到达日期,我需要获取 5 个月及之前到达的记录
- mysql - 复杂查询 SQL,带有嵌套查询
- python - vscode远程容器中的自动完成python
- node.js - ReferenceError: primordials is not defined 安装 Semantic UI 时出现错误
- angular - Angular9:类型'可观察的
>' 不可分配给类型 'Observable ' - python - 如何在 Tensorflow 中重新批处理张量?
- spring - spring 云流 kafka 消费者 clientId 匿名
- c# - C# 库如何检测 app.config 是否存在,如果不存在则手动加载配置文件?
- java - 如何按参数运行不同的测试套件?