如果我想检查TreeMap中第一个索引位置的值是否为xyz,那么请执行xyz 否则,如果第一个索引位置的值是abc,则执行abc。我怎么能写这个?因为我想在TreeMap中访问排列的索引。我想按顺序逐个访问TreeMap的排序键。需要帮助
答案 0 :(得分:1)
最快和最丑的黑客可能只是
List<KeyType> keyList = new ArrayList<>(myTreeMap.keySet());
KeyType nthKey = keyList.get(nthIndex);
但是当我想按索引查找条目时,我会问自己为什么我首先使用TreeMap
?使用List
并调用sort
?
答案 1 :(得分:1)
//this code iterates through all the keys in sorted order
treeMap.keySet().forEach(key -> {
//use key to do whatever you need
});
//this code iterates through all entries (from first, second, third, ... to last)
tree.entrySet().forEach(entry -> {
key = entry.getKey();
value = entry.getValue();
//use key and value to do whatever you need
});
//this codes finds the first key whose value equals the desired value
Object key = tree.entrySet().stream()
.filter(e -> e.getValue().equals(desiredValue))
.map(Entry::getKey)
.findFirst()
.get();