将LinkedHashMap迭代到第x个元素的最佳方法是什么?
for (Entry<String, Integer> entry : existingFile.entrySet() )
{
builder.append("{" + entry.getKey() + "," + entry.getValue() + "} ");
}
这遍历所有元素,我怎么能阻止它在第5个元素说?
答案 0 :(得分:5)
使用计数器:
int counter = 0;
for (Entry<String, Integer> entry : existingFile.entrySet() )
{
if (counter == 5)
break;
builder.append("{" + entry.getKey() + "," + entry.getValue() + "} ");
counter++;
}
答案 1 :(得分:2)
使用Java 8,您可以创建一个流并将其限制为5个项目:
existingFile.entrySet().stream()
.limit(5)
.forEach(e -> builder.append("{"
+ e.getKey() + ","
+ e.getValue() + "} "));