从地图中获取第一个值和第二个值的最佳方法是什么。
我正在尝试阅读tableLists
地图并从地图中获取first and second value
。
以下是我所拥有的代码ReadTableConnectionInfo
是该类。
private final LinkedHashMap<String, ReadTableConnectionInfo> tableLists;
ReadTableConnectionInfo table = tablePicker();
private ReadTableConnectionInfo tablePicker() {
Random r = new SecureRandom();
ReadTableConnectionInfo table;
if (r.nextFloat() < Read.percentageTable / 100) {
table = get first value from tableLists map
} else {
table = get second value from tableLists map
}
return table;
}
答案 0 :(得分:1)
假设您确定您的LinkedHashMap包含至少两个值,您可以这样做:
Iterator<Map.Entry<String, ReadTableConnectionInfo >> it = tableLists.entrySet().iterator();
if (r.nextFloat() < Read.percentageTable / 100) {
table = it.next().getValue();
} else { //since you have an else, you have to re-ignore the first value just below
it.next(); // ignoring the first value
table = it.next().getValue(); //repeated here in order to get the second value
}
答案 1 :(得分:1)
LinkedHashMap值的迭代按插入顺序排序。所以values()就是你所需要的:
Iterator it = values().iterator();
Object first = it.next().getValue();
Object second = it.next().getValue();