public static void main(String[] args) { String key="additionalData,balanceAmount,bankCardType,channelOrderNo,commissionAmount,liquidationDate,merchantNo,storeCode,storeName,payMethod,refundAmount,refundCompletionTime,refundOriginalOrderNo,terminalId,terminalSerialNumber,tradeAmount,tradeNo,tradeStatus,tradeType"; String values = "858405812004929,14505386,2023-05-05 00:03:40,,2570,6,0,2564,2,3,1,145053869722323050500032700183,,1683216206175,2023050522001468531436244681,2023-05-05,2088242754868530,1,\n" + "858405812004929,14505386,2023-05-05 00:03:44,,3000,7,0,2993,2,3,1,145053869222323050500033700219,,1683216217824,2023050522001417661456876042,2023-05-05,2088222966217663,0,";// 将key字符串分隔为属性名数组 String[] keys = key.split(","); // 将values字符串分隔为值数组 String[] lines = values.split("\n"); // 使用Java 8 Stream API将数组转换为List<Map<String, String>> List<Map<String, String>> resultList = Arrays.stream(lines) .map(line -> { String[] valuesArray = line.split(","); Map<String, String> map = new HashMap<>(); for (int i = 0; i < keys.length; i++) { if (valuesArray.length > i) { map.put(keys[i], valuesArray[i]); } } return map; }) .collect(Collectors.toList()); // 输出结果 System.out.println(resultList); }
另外一种写法 就是只有一个map的情况下
// public static void main(String[] args) {// String keys = "merchantNo,terminalId,transactionTime,refundCompletionTime,tradeAmount,commissionAmount,refundAmount,balanceAmount,transactionType,payMethod,tradeStatus,transactionNo,refundOriginalOrderNo,terminalSerialNumber,channelOrderNo,liquidationDate,userId,bankCardType";// String values = "858405812004929,14505386,2023-05-05 00:03:40,,2570,6,0,2564,2,3,1,145053869722323050500032700183,,1683216206175,2023050522001468531436244681,2023-05-05,2088242754868530,1,";// String[] keysArray = keys.split(",");// Map<String, String> map = IntStream.range(0, keysArray.length)// .mapToObj(i -> new AbstractMap.SimpleEntry<>(keysArray[i], values.split(",")[i]))// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));//// System.out.println("-------------------------" + map);// }
获取对象中的所有 属性值名称
// ShopMerchantBill shopMerchantBill = new ShopMerchantBill();
// Field[] fields = shopMerchantBill.getClass().getDeclaredFields();
// // 遍历对象的所有属性
// for (Field field : fields) {
// field.setAccessible(true);
// System.out.print(field.getName()+",");
// }
其中 field.setAccessible(true); 是按照字母排序