4

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.

coder
  • 203
  • 5
  • 15
  • How about breaking the loop after 5 iterations (controlled by `int` variable)? – Arrvi Feb 22 '16 at 21:59
  • This depends on what version of Java you are using... With Java 7- the solution for this would be vastly different from what it would be with Java 8+. Also, you say you want the 5 first values: in what? A collection, an array? – fge Feb 22 '16 at 21:59
  • @fge android uses Java 7 – Mussa Feb 22 '16 at 22:00
  • @Mussa no it doesn't. Android, as far as I know, still doesn't have any viable JSR 203, or JSR 292, implementation – fge Feb 22 '16 at 22:01
  • Can you please define "values"? You `.append()` to some `text` but do not even tell what this `text` is... – fge Feb 22 '16 at 22:04

4 Answers4

6

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();
    ...
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
5
int i = 0;
for (String sentences : lhs) {       
    if (i > 4) break; 
    text.append(sentences);
    i++;
}
Mussa
  • 1,463
  • 21
  • 25
  • Thank you very much, it works perfectly. This is exactly the type of solution that I was trying to figure out. – coder Feb 22 '16 at 22:10
  • @coder and what is supposed to happen if the input set has _less elements_ than what you are waiting for? – fge Feb 22 '16 at 22:12
  • @fge it would still work because it only stops if it is greater than 4. – coder Feb 22 '16 at 22:17
  • 1
    @fge it will stop if *i* is greater than 4 **or** if *lhs* runs out of items – Mussa Feb 22 '16 at 22:19
5

If you had java8, then I would suggest something like this:

yourLinkedHashSet
    .stream()
    .limit(5)
    .forEachOrdered(text::append);

Explanation:

  • stream() will take one String after another from the collection
  • limit(5) will stop the calculations after five elements are processed
  • forEachOrdered(...) takes an action for each item, one after another
  • text::append is the action to be done per item
slartidan
  • 20,403
  • 15
  • 83
  • 131
0

You can use subList without counter declaration

  Iterator<String> iter = new ArrayList<>(lhs).subList(5, lhs.size())
    .iterator();
  while (iter.hasNext()) {
    text.append(iter.next());
  }
luk4
  • 7
  • 3