public static void compareTravelBalance(Map<String, Integer> travelCosts, Map<String, Integer> travellerBalances){
Set set = travelCosts.entrySet();
Iterator iterator = set.iterator();
Set set1 = travellerBalances.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
Map.Entry mapEntry= (Map.Entry) iterator1.next();
int cost = (Integer) mentry.getValue();
int balance = (Integer) mapEntry.getValue();
if(travellerBalances.containsKey(mentry.getKey())){
if(cost>balance){
System.out.println("Insufficient funds for "+mentry.getKey()+": Cost: "+cost+" Balance: "+balance);
}
else if(cost<=balance){
System.out.println("Approved! for: "+mentry.getKey()+": Cost: "+cost+" Balance: "+balance);
}
}
else{
System.out.println("Traveller ID "+mentry.getKey()+" does not exist");
}
}
}
上面是我的代码。我有两个 CSV,我将其数据保存到两个不同的 TreeMap 中 - TravelCosts 和 TravellerBalances。键值对是 TravellerId 作为键,travelCost 作为第一个 TreeMap 中的值,travelBalance 作为第二个 TreeMap 中的值。
我正在尝试根据 TravellerId 比较来自不同 map 的两个值。因此,如果成本>余额,则应打印资金不足。如果成本<=余额,则应打印Approved。如果没有键匹配,则旅行者不存在。
我附上了 CSV,它将向您显示我在 map 中的数据。
问题是:如果您查看数据,就会发现它正在比较 Travellerid 2001 与 2002 年以及 2002 年与 2003 年等。相反,它应该说 2001 年不存在。 我希望我说得有道理。请询问您是否需要更多信息。
谢谢。 Travel Costs-first col is travellerId and the third col is travelCost
Travel Balances - the first col is travellerId and third col is travelBalance
最佳答案
在设计程序时,并行数据结构通常很难使用。在这种情况下,最好创建一个包含 id
、costs
和 balance
的 Traveler 类。将它们存储在 Map 中,其中键是 Traveller.id。读取 CSV 时,必要时添加旅客,否则更新现有旅客成本
或余额
。 id
不必位于 Traveler 中,因为它位于 Map 键中,但通常是个好主意。
关于java - 根据键值对比较两个 TreeMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575399/