How to iterate through LinkedHashMap to the xth element?

1.8k Views Asked by At

What is the best way to iterate through a LinkedHashMap to the xth element ?

for (Entry<String, Integer> entry : existingFile.entrySet() )
            {

                builder.append("{" + entry.getKey() + "," + entry.getValue() + "}   ");

            }

This iterates to through all the elements, how can I stop it say at the 5th element ?

2

There are 2 best solutions below

0
On BEST ANSWER

Use a counter:

int counter = 0;

for (Entry<String, Integer> entry : existingFile.entrySet() )
{
    if (counter == 5)
        break;

    builder.append("{" + entry.getKey() + "," + entry.getValue() + "}   ");
    counter++;
}
0
On

With Java 8 you can create a stream and limit it to 5 items:

existingFile.entrySet().stream()
     .limit(5)
     .forEach(e -> builder.append("{"
          + e.getKey() + "," 
          + e.getValue() + "}   "));