I have a LinkedHashSet which contains multiple number of values.
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
I want to iterate through the set of values and display the first five values from the number of items stored in the set. I have used a for loop to iterate through values and display data, see below:
for (String sent : lhs) {
text.append(sent);
}
This outputs all the values stored in the LinkedHashSet. What alterations should I make to my code in order to only get the first 5 values from the set.
You can get your sets Iterator
Iterator<String> it = yourSet.iterator();
and move to next()
element N times (assuming that it still hasNext()
element)
int counter = 0;
while(it.hasNext() && counter++ < N){
String element = it.next();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With