Anil
Anil

Reputation: 2465

Retrieving n values from treemaps in java

I'm using treemaps in my java program. The output of the program is a sorted map as follows

[cat=1, dog=1, pin=3, ball=4, mice=4..... and so on]

I want to display only first 3 values of the map instead of displaying the whole map. I want my output as follows

cat=1
dog=1
pin=3

How can i do this?

Upvotes: 0

Views: 58

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

Add a count variable, set it to zero, and break out of the loop when it reaches three:

int count = 0;
for (/* the loop that goes through all elements of the tree map...*/) {
    // Do your printing...
    count++;
    if (count == 3) break;
}

I am purposely posting only a skeletal solution, assuming that this is a homework.

Upvotes: 2

Related Questions