4

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.

6
  • 3
    Why? Better use List. You could do: Arrays.asList(ligature).subList( 0,5 ).toArray(); But that is cumbersome. Commented Aug 15, 2018 at 8:41
  • @RobAu .toArray(new String[5]) would be needed if one wants to get a typed array back Commented Aug 15, 2018 at 8:45
  • @Lino that is silly. You just need toArray(new String[0]) as the argument is only used to determine the type. Commented Aug 15, 2018 at 8: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. Commented Aug 15, 2018 at 8:50
  • 1
    @Lino. Didn't know! It also sets elements in given array to null if it is bigger. Thanks! Commented Aug 15, 2018 at 8:53

2 Answers 2

12

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

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

// for an array
Arrays.copyOfRange
Sign up to request clarification or add additional context in comments.

4 Comments

Agreed. subList is almost always better, but tricky as you can modify the original list by accident as it is just a view on the List.
@RobAu Arrays.copyOfRange for such a case
@Eugene Collections.unmodifiableList will return an list that cannot be modified. Arrays.copyOfRange will also not deep-copy the elements inside?
@RobAu you right, me wrong, System.arrayCopy does not do a deep copy.
3

Arrays class has a method for this:

Arrays.copyOfRange(ligature, 0, 5);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.