TreeMap Sorted Positions Access

210 Views Asked by At

If I want to check that the value present at first index position in a TreeMap is xyz then do xyz Else if the value present at the first index position is abc then do abc. How I will be able to write this? Because I want to access arranged indices in a TreeMap. I want to access sorted keys of a TreeMap one by one in order. Help required

2

There are 2 best solutions below

6
On BEST ANSWER
//this code iterates through all the keys in sorted order
treeMap.keySet().forEach(key -> {
    //use key to do whatever you need
});

Edit

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

Edit2

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

The quickest and ugliest hack might simply be

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

but I'd be asking myself why am I using a TreeMap in the first place, when I want to look up entries by index? Would it be more efficient to use a List and call sort?