3

I want to pick first N elements from a list in java

String[] ligature = new String{there,is not,a,single,person,who,knows,the,answer};

Now I want to pick first 5 elements from this.something like

Stiring[] selectedLigature = ligature[0:4];

I want to do it without using for loop.

Jack Flamp
  • 1,183
  • 1
  • 14
  • 31
user_3pij
  • 1,242
  • 8
  • 20
  • 3
    Why? Better use `List`. You could do: `Arrays.asList(ligature).subList( 0,5 ).toArray()`; But that is cumbersome. – Rob Audenaerde Aug 15 '18 at 08:41
  • @RobAu `.toArray(new String[5])` would be needed if one wants to get a typed array back – Lino Aug 15 '18 at 08:45
  • @Lino that is silly. You just need `toArray(new String[0])` as the argument is only used to determine the type. – Rob Audenaerde Aug 15 '18 at 08:48
  • @RobAu if the length of the input array is equal or bigger than the `List` then it is used. At least in the case of `ArrayList`. – Lino Aug 15 '18 at 08:50
  • 1
    @Lino. Didn't know! It also sets elements in given array to `null` if it is bigger. Thanks! – Rob Audenaerde Aug 15 '18 at 08:53
  • @Lino is should *always* be `new String[0]` without an actual size https://stackoverflow.com/questions/51766615/list-to-varargs-with-pre-difined-size-or-without-size/51775139#51775139 – Eugene Aug 15 '18 at 09:11

2 Answers2

9

Do not stream this simple case, there is subList for this:

// for a List
yourList.subList(0, 5)...

// for an array
Arrays.copyOfRange
Eugene
  • 110,516
  • 12
  • 173
  • 277
3

Arrays class has a method for this:

Arrays.copyOfRange(ligature, 0, 5);
Jack Flamp
  • 1,183
  • 1
  • 14
  • 31