gpt4 book ai didi

java - 如何比较两个 HashMap>

转载 作者:太空宇宙 更新时间:2023-11-04 14:40:30 26 4
gpt4 key购买 nike

我想将从 Excel 文件中读取的数据(键是第 1 列,值是第 2 列)中放入 HashMap 的数据与从 SQL 查询获取的数据进行比较。起初我使用 HashMap< String, String> 来做到这一点,因为我必须只比较 < key, value> 对,但现在我必须比较 < key, list> 并且我有点卡住了。这是我读取 xls 文件的代码:

public class ReadExcel {

HashMap<String, List<String>> result = new HashMap<String, List<String>>();

public HashMap<String, List<String>> process() {
try
{
result.clear();

FileInputStream file = new FileInputStream(new File("C:/some.xlsx"));

//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);

//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);

//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();


while (rowIterator.hasNext()) {
List<String> xlsList = new ArrayList<String>();

Row row = rowIterator.next();
Cell cell = row.getCell(1);
Cell cell2 = row.getCell(2);
String key ="";
String value="";
xlsList.clear();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
key = getStringCellValue(cell);
value = getNumericCellValue(cell2);
break;

case Cell.CELL_TYPE_STRING:
key = getStringCellValue(cell);
value = getStringCellValue(cell2);
break;

}

xlsList.add(value);
result.put(key, xlsList);
}
}
}

例如在我的 Excel 文件中

row 1: column 1 = car, column 2 = blue
row 2: column 1 = car, column 2 = yellow.

当我运行 Excel 阅读器时,它会将值“blue、yellow”很好地放在 HashMap 中的“car”键下。例如,当我有:

row 1: column 1 = car,  column 2 = blue
row 2: column 1 = car, column 2 = yellow
row 3: column 1 = year, column 2 = 1990
row 4: column 1 = year, column 2 = 1999

它仅显示:car=[yellow],year=[1999]。它只需要最后一个值,如果不是重复的键,这工作得很好。

第一个问题:我怎样才能做得更好?如果我在第 1 行获得相同的键,并且仅在第 1 行的键相同的情况下仅获取该键一次并存储第 2 行的所有值?

这是我从 SQL 数据库提取数据的代码:

public class DB {
HashMap<String, List<String>> result = new HashMap<String, List<String>>();

public HashMap<String, List<String>> process() {

result.clear();

Connection conn = null;
Statement stmt = null;
List<String> carColour = new ArrayList<String>();

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql1 = "SOME SQL SELECT STATEMENT THAT RETURNS 2 or more lines, by that i mean "car" has 2 values or more";
ResultSet rs = stmt.executeQuery(sql1);

while(rs.next()){
carColour.add(rs.getString("colour")); // i select the column "colour"
result.put("car", carColour); // i put "car" as key, and "blue" and "yellow" as values
...................................
}
} catch...
}

数据库的这段代码工作正常,但如果我想提取更多列,例如“颜色”或“年份”,我必须为所有列创建列表,如果我有 20 列要提取,它可以非常耗时。

第二个问题:我怎样才能更轻松地做到这一点,而不是创建 20 个列表?(也许使用相同的列表和 list.clear(); 它?)(这取决于,因为如果我有 30 列,而我只需要 20 列,我可以 getString("column") 全部并删除我不想要的,但是如何?

以下是比较代码:

final Map<String, Boolean> comparisonResult = compareEntries(dbResult, xlsResult);
for(final Entry<String, Boolean> entry : comparisonResult.entrySet()){
if (entry.getValue() == false){
System.out.println("------------------------------------------------------------------------");
System.out.println("| Comparison FAILED | Value not matching! Column name --> " + entry.getKey() + " |");
}
}
System.out.println("------------------------------------------------------------------------");
System.out.println("DB consistency check finished.");

...................................................... ......................................

public static <K extends Comparable<? super K>, V>
Map<K, Boolean> compareEntries(final Map<K, V> dbResult,
final Map<K, V> xlsResult){
final Collection<K> allKeys = new HashSet<K>();
allKeys.addAll(dbResult.keySet());
allKeys.addAll(xlsResult.keySet());
final Map<K, Boolean> result = new TreeMap<K, Boolean>();
for(final K key : allKeys){
result.put(key, dbResult.containsKey(key) == xlsResult.containsKey(key) && Boolean.valueOf(equal(dbResult.get(key), xlsResult.get(key))));
}
return result;
}

private static boolean equal(final Object obj1, final Object obj2){
return obj1 == obj2 || (obj1 != null && obj1.equals(obj2));
}

最后一个问题:如何改进代码来比较两个 HashMap(String, List< String>),或者如何逐步做得更好?谢谢!

最佳答案

您的 ReadExcel 读取循环存在严重问题:您总是创建一个新列表,而不是重用已由键映射的 List,因此您最终会得到只有一个(最后一个)值的列表。

这是解决此问题的方法(使用 Java 8):

// ...
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Cell keyCell = row.getCell(1);
Cell valCell = row.getCell(2);

String key = getStringCellValue(keyCell);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
value = getNumericCellValue(valCell);
break;
case Cell.CELL_TYPE_STRING:
value = getStringCellValue(valCell);
break;
}
}

// this line only compiles since Java 8
result.computeIfAbsent(key, k -> new HashSet<Object>()).add(value);
}

如果您还没有使用 Java 8,请快速下载,或将上面的最后一行替换为:

Set<Object> list = result.get(key);
if (list == null) result.put(key, list = new HashSet<Object>());
list.add(value);

Map 对象的比较相当简单 - 您可以使用 equals 直接比较它们:

if (map1.equals(map2)) {
// both maps are equal!
} else {
// maps are NOT equal!
}

当然,这只会产生truefalse。如果您想了解详细信息(哪些条目不同),则需要您自己完成。

关于java - 如何比较两个 HashMap<String, List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25003745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com