[英]Multiple keys to 1 key but values as sum
顯然,我找到了與此相關的另一個主題,但是它並沒有任何幫助。
我的問題:輸出確實
如下所示,問題出在if語句中。 那么if語句應該怎么做?
如果其中不包含該密鑰,則只需將licenseplateList.get(i)作為密鑰,然后添加值kmperlineList.get(i)
對於整個代碼,請檢查: https : //pastebin.com/jaSTm1DR
if (before) {
// does our map already contain this license?
if (nachtMap.containsKey(licenseplateList.get(i))) {
kmperlineList.get(i).replaceAll(",", ".");
// then remove that one, add new one but have the sum of the values
// is this extra ) after ".get(i)" correct?
Double sum = nachtMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
nachtMap.put(licenseplateList.get(i), sum);
}
// if it doesnt contain the license yet, just put it in there
else {
kmperlineList.get(i).replaceAll(",", ".");
nachtMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
// if its not before 06:00
else {
// als de tijd na 17:30 is
if (after) {
if (nachtMap.containsKey(licenseplateList.get(i))) {
Double sum = nachtMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
nachtMap.put(licenseplateList.get(i), sum);
} else {
kmperlineList.get(i).replaceAll(",", ".");
nachtMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
// otherwise it's always day
else {
// again: does the map already contain this license plate?
if (dagMap.containsKey(licenseplateList.get(i))) {
System.out.println("works");// debug
kmperlineList.get(i).replaceAll(",", ".");
// then get the sum of the values, but only 1 time the key
Double sum = dagMap.remove(licenseplateList.get(i)) + Double.parseDouble(kmperlineList.get(i));
dagMap.put(licenseplateList.get(i), sum);
}
// if the map does not contain the license plate
else {
kmperlineList.get(i).replaceAll(",", ".");
dagMap.put(licenseplateList.get(i), Double.parseDouble(kmperlineList.get(i)));
}
}
}
您的代碼過於復雜和多余。
但是首先,似乎您的文件使用的是非美國數字格式( 1000,00
,而不是1000.00
),因此您應該使用具有正確Locale
NumberFormat
來解析數字,而不是使用Double.parseDouble
來解析Java語法數字。
假設使用Java 8(因為所有早期版本現在都已經停產),您的代碼可以簡化為:
double kmperline = NumberFormat.getNumberInstance(Locale.GERMANY)
.parse(kmperlineList.get(i)).doubleValue();
Map<String, Double> mapToUpdate = (before || after ? nachtMap : dagMap);
mapToUpdate.merge(licenseplateList.get(i), kmperline, Double::sum);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.