Retrieve the first elements of an Integer list

5

I have a list ArrayList<Integer> list = new ArrayList<Integer>(); where I have over 40,000 records. I wonder if you have a way to get only the top 10,000. I know you have to for and move to a new list, but this requires a lot of processing.

Would it have a simpler way? Or with Lambda?

    
asked by anonymous 16.02.2016 / 17:59

2 answers

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

// Adiciona os 40 mil registros...

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

Maybe, to avoid wasting processing, you'd prefer to work with Stream s directly, avoiding using collect method . In this case, you would do this:

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

The key is to use limit .

    
16.02.2016 / 18:05
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.

Then, in your case:

ArrayList<Integer> array = new ArrayList<Integer>();
....
// Adicionar items ao array
....
List<Integer> array2 = array.subList(0,10000);
    
16.02.2016 / 18:07