Take N elements from list

This example will show how to get the first N elements from an ArrayList using java, java 8 and guava.

Straight up Java

This snippet will truncating a ArrayList to a given number of elements in java using List.subList.

@Test
public void limit_array_list_size_java () {

    List<Integer> contestents = new ArrayList<Integer>(8);
    contestents.add(1);
    contestents.add(2);
    contestents.add(3);
    contestents.add(4);
    contestents.add(5);
    contestents.add(6);
    contestents.add(7);
    contestents.add(8);
    contestents.add(9);

    List<Integer> contestWinners = contestents.subList(0, 5);

    assertEquals(5, contestWinners.size());
}

Java 8

Similar to the snippet shown how to create a stream from a function and java 8 stream intermediate operations java 8 Stream.limit is used to truncate elements in an ArrayList based on a specified size.

@Test
public void limit_array_list_size_java8 () {

    List<Integer> contestents = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);

    List<Integer> contestWinners = contestents
            .stream()
            .limit(5)
            .collect(Collectors.toList());

    assertEquals(5, contestWinners.size());
}

Google Guava

Using guava FluentIterable we will truncate an Iterable to the specified number of elements.

@Test
public void limit_array_list_size_guava() {

    List<Integer> contestents = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);

    List<Integer> contestWinners = FluentIterable.from(contestents)
            .limit(5).toList();

    assertEquals(5, contestWinners.size());
}