How to compare two values in TreeMap?

user10183885

I have a TreeMap and I want to compare its i and i+1 value in it. How can I do that. I know that TreeMap is sorted based on its keys but I want to compare the values and can't use sorting as I will loose original form. I want something like this but in TreeMap-

int a[] = new int[n];
for (int i = 0; i < a.length - 1; i++)
{
     if (a[i] > a[i + 1])
    {
         c++;
    }
}
Veselin Davidov

Well you can do it like that:

        TreeMap<Integer,Integer> tree=new TreeMap<>();          
        tree.put(1,5);
        tree.put(2,6);
        tree.put(3,4);
        tree.put(4,4);   

        Entry<Integer,Integer> entry=tree.firstEntry();
        int c=0;
        while(tree.higherEntry(entry.getKey())!=null) {
            if(entry.getValue()>tree.higherEntry(entry.getKey()).getValue())
                c++;
            entry=tree.higherEntry(entry.getKey());
        }

Using the higherEntry, higherKey etc.

By the way in your example you will get an ArrayIndexOutOFBound I think because of a[i + 1]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related