35

I want the first n elements of some List. From what I can tell, I have two options: take(n) and getRange(0, n).

  1. What's the difference between them?
  2. When would I use one over the other (assuming I always want the first n elements)?

1 Answer 1

59

The most obvious difference is that take() can only use elements at the beginning, you can combine it with skip() like list.skip(3).take(5) to get similar behavior though.
list.take() is lazy evaluated which works nice with functional style programming and might be more efficient if the elements aren't actually iterated over later.
list.take() also is tolerant when there aren't as many elements in the list as requested. take() returns as many as available, getRange() throws. take() is available on all iterables (also streams), getRange() is only available by default on list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.