Retrieve the first elements of an Integer list

Asked

Viewed 1,382 times

5

I have a list ArrayList<Integer> list = new ArrayList<Integer>(); where I have over 40,000 records. I wonder if there’s a way to get only the first 10,000. I know you can make one for and move on to a new list, but that takes a lot of processing.

Would it have a simpler way? Or with Lambda?

  • How You Get 40k Items?

2 answers

6


List<Integer> list = new ArrayList<>();

// Adiciona os 40 mil registros...

List<Integer> list2 = list.stream().limit(10000).collect(Collectors.toList());

Perhaps, to avoid wasting processing, you prefer to work with Streams directly, avoiding using the method collect. In this case, you would do it:

Stream<Integer> stream = list.stream().limit(10000);

The secret is to use the method limit.

5

According to the documentation, it has the function:

List<E> subList(int fromIndex, int toIndex)
//Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

So in your case:

ArrayList<Integer> array = new ArrayList<Integer>();
....
// Adicionar items ao array
....
List<Integer> array2 = array.subList(0,10000);
  • 1

    I think he’s trying to avoid copies

  • I edited the solution.. Now, I have two instances that point to the same list. I ran some tests.. When changing the item of the array2, the array is also changed - that is, they have the same reference.

  • Great solution. :)

  • 1

    Thanks for the warning... A silly mistake that would cost a little memory hehe

  • This is the most efficient and correct solution if the idea is to reference a part of the list without changing the content, for example if you want to pass to a method. It creates only a new object that points to the original internal vector. However, it is good to always try to work with immutable lists to avoid headaches, otherwise the side effects of this will make you have nightmares.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.