TreeMap 排序位置访问

TreeMap Sorted Positions Access

如果我想检查 TreeMap 中第一个索引位置的值是否为 xyz,则执行 xyz 否则,如果第一个索引位置的值是 abc,则执行 abc。我怎么才能写这个?因为我想访问 TreeMap 中排列的索引。我想按顺序一个一个地访问 TreeMap 的排序键。需要帮助

最快和最丑陋的黑客可能只是

List<KeyType> keyList = new ArrayList<>(myTreeMap.keySet());
KeyType nthKey = keyList.get(nthIndex);

但我会问自己,当我想按索引查找条目时,为什么首先要使用 TreeMap?使用 List 并调用 sort 会更有效吗?

//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
});

编辑2

//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();