Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain first 5 values from a LinkedHashSet?

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.

like image 492
coder Avatar asked Dec 05 '22 18:12

coder


1 Answers

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();
    ...
}
like image 180
Pshemo Avatar answered Dec 09 '22 14:12

Pshemo