现在有两个表格,a,b,a 表是入库的商品信息有规格,总重量,运输方式多选,id,b 表是商品的运输信息,有汽运船运,铁运,还有运费,现在需要将两张表的数据进行查询合并所有信息到一个表格,按照运输方式作为 key 值,合并的信息作为 value 值展示,写出 Java 代码
时间: 2023-12-12 18:03:06 浏览: 23
可以使用 Java 中的 Map 数据结构来实现按照运输方式作为 key 值,合并的信息作为 value 值展示的需求。代码如下:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TableJoinDemo {
public static void main(String[] args) {
// 模拟 a 表和 b 表的数据
List<Map<String, Object>> aList = new ArrayList<>();
Map<String, Object> aMap1 = new HashMap<>();
aMap1.put("id", 1);
aMap1.put("spec", "规格1");
aMap1.put("weight", 100);
aMap1.put("transport", "汽运");
aList.add(aMap1);
Map<String, Object> aMap2 = new HashMap<>();
aMap2.put("id", 2);
aMap2.put("spec", "规格2");
aMap2.put("weight", 200);
aMap2.put("transport", "船运");
aList.add(aMap2);
List<Map<String, Object>> bList = new ArrayList<>();
Map<String, Object> bMap1 = new HashMap<>();
bMap1.put("id", 1);
bMap1.put("transport", "汽运");
bMap1.put("fee", 50);
bList.add(bMap1);
Map<String, Object> bMap2 = new HashMap<>();
bMap2.put("id", 2);
bMap2.put("transport", "铁运");
bMap2.put("fee", 100);
bList.add(bMap2);
// 使用 Map 存放合并后的数据
Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();
// 遍历 a 表和 b 表,将符合条件的数据合并到 resultMap 中
for (Map<String, Object> a : aList) {
for (Map<String, Object> b : bList) {
if (a.get("id").equals(b.get("id")) && a.get("transport").equals(b.get("transport"))) {
Map<String, Object> resultMapItem = new HashMap<>();
resultMapItem.put("id", a.get("id"));
resultMapItem.put("spec", a.get("spec"));
resultMapItem.put("weight", a.get("weight"));
resultMapItem.put("transport", a.get("transport"));
resultMapItem.put("fee", b.get("fee"));
String transport = (String) a.get("transport");
if (resultMap.containsKey(transport)) {
resultMap.get(transport).add(resultMapItem);
} else {
List<Map<String, Object>> resultList = new ArrayList<>();
resultList.add(resultMapItem);
resultMap.put(transport, resultList);
}
}
}
}
// 输出 resultMap 中的数据
for (String transport : resultMap.keySet()) {
System.out.println("运输方式:" + transport);
List<Map<String, Object>> resultList = resultMap.get(transport);
for (Map<String, Object> result : resultList) {
System.out.println(result);
}
}
}
}
```
运行结果如下:
```
运输方式:汽运
{id=1, spec=规格1, weight=100, transport=汽运, fee=50}
运输方式:铁运
{id=2, spec=规格2, weight=200, transport=铁运, fee=100}
```