Search code examples
javasortingtreemap

TreeMap Sorted Positions Access


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


Solution

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