从地图中检索第一个值和第二个值
问题描述:
从地图中获取第一个值和第二个值的最佳方法是什么? 我正在阅读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;
}
答
假设你确定你的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
}
答
LinkedHashMap的值迭代由插入顺序排序。所以值()是你需要的:
Iterator it = values().iterator();
Object first = it.next().getValue();
Object second = it.next().getValue();
你是什么意思第一和第二,按什么顺序? – Drakosha 2013-02-24 03:42:19
我修改了我的问题,抱歉它是linkedhashmap。所以我需要第一个和第二个值插入它的方式。 – AKIWEB 2013-02-24 03:44:09
元素的顺序不能保证在HashMap – anoopelias 2013-02-24 03:44:33