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
设置为值
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 :(得分: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());
}
答案 1 :(得分:0)
只是if(percent > map.get("new") && percent < map.get("previous"))
?如果这实际上是您所要求的,那么您应该停留在地图的javadoc上,然后再继续。