2012-05-22 33 views
-1
LinkedHashMap<String, Double> testMap = (LinkedHashMap<String, Double>) sortByValue(commands.get(commandWithMaxNegativeOffset).getDataUsageCriteria()); 

從以上,testMap遺囑內的值的升序像{New=30.0, Previous=70.0}所以我想要做的是在的if/else循環類似下面,按照目前的我現在已經硬編碼只是爲了更有意義,但我想使用testMap而不是硬編碼。我想設置key的值,如果條件得到匹配by using key/value pair from map設置的HashMap的關鍵設定器

double percent = r.nextDouble()*100; 

if(percent > 1.0 && percent < 70.0(how can I use 70 from testMap instead of hardcoding)) { 
//what to put below in place of Previous 
    commands.get(commandWithMaxNegativeOffset).setDataCriteria(Use the Key of 70.0 i.e Previous); 
} else if(percent > 71 && percent < 100){ 
    commands.get(commandWithMaxNegativeOffset).setDataCriteria(Use the Key of 30.0 i.e New); 
} 
+0

會不會有永遠是你'Map'只有兩個鍵 - 值對?將所有值加在一起總是等於100.0(例如,30.0 + 70.0 = 100.0)? – creemama

+0

@creemama,是的只有兩個關鍵值對總是總計爲100. – AKIWEB

回答

1

如果我理解正確的話,下面可能是你在找什麼:

final LinkedHashMap<String, Double> testMap = new LinkedHashMap<String, Double>(); 
testMap.put("New", Double.valueOf(30.0)); 
testMap.put("Previous", Double.valueOf(70.0)); 

// The map contains two entries. 
Set<Map.Entry<String, Double>> entries = testMap.entrySet(); 
Iterator<Map.Entry<String, Double>> it = entries.iterator(); 
Map.Entry<String, Double> firstEntry = it.next(); 
Map.Entry<String, Double> secondEntry = it.next(); 

Random r = new Random(); 
double percent = r.nextDouble() * 100; 

// percent is a number between 0.0 and 100.0 
if (percent < secondEntry.getValue().doubleValue()) // between 0.0 and 70.0 exclusive 
{ 
    commands.get(commandWithMaxNegativeOffset).setDataCriteria(secondEntry.getKey()); 
} 
else // between 70.0 inclusive to 100.0 (100.0 - 70.0 = 30.0) 
{ 
    commands.get(commandWithMaxNegativeOffset).setDataCriteria(firstEntry.getKey()); 
} 
0

只是if(percent > map.get("new") && percent < map.get("previous"))?如果這實際上是你問的問題,那麼在繼續之前,應該停止在javadoc for map。

+0

我可以這樣做,但它會被硬編碼。如果你看看我的問題,testMap包含'{New = 30.0,Previous = 70.0}'。我想在我的if else循環中使用這個testMap。 – AKIWEB

+0

@Nevzz03 map有一個方法'values()'來獲取一組值。對於密鑰集,有類似的方法稱爲'keySet()'AFAIR。使用它,迭代它,你將不必使用硬編碼的鍵值 – dantuch

+0

你能告訴我基於我的代碼的例子。這將有很大的幫助。 – AKIWEB