How to Return the First N Elements in Java

The challenge

Create a method take that accepts a list/array and a number n, and returns a list/array array of the first n elements from the list/array.

If you need help, here’s a reference:

https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int)

Test cases

import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;
import java.util.*;

public class SolutionTest {
    @Test
    public void basicTests() {
        assertArrayEquals("should return the first 3 items", new int[]{0, 1, 2}, ZywOo.take(new int[]{0, 1, 2, 3, 5, 8, 13}, 3));
        assertArrayEquals("should return 0 items", new int[0], ZywOo.take(new int[]{0, 1, 2, 3, 5, 8, 13}, 0));
        assertArrayEquals("empty array should return empty array", new int[0], ZywOo.take(new int[0], 3));
    }
    
    @Test
    public void randomTests() {
      for (int i = 0; i < 100; i++) {
        int n = (int)Math.floor(100 * Math.random());
        int[] randomArray = generateRandomArray();
        
        assertArrayEquals("Testing with array " + Arrays.toString(randomArray) + " and n = " + n, solution(randomArray, n), ZywOo.take(randomArray, n));
      }
     
    }
    
    private int[] solution(int[] arr, int n) {
      return arr.length > 0 && arr.length > n ? Arrays.copyOfRange(arr, 0, n) : arr;
    }
    
    private int[] generateRandomArray() {
      int length = (int)Math.floor(100 * Math.random());
      int min = (int)Math.floor(-100 * Math.random());
      int max = (int)Math.floor( 100 * Math.random());
      return new Random().ints(length, min, max).toArray();
    }
}

The solution in Java

Option 1:

public class ZywOo {
  public static int[] take(int[] arr, int n) {
    if (arr.length==0) return arr;
    if (n>arr.length) return arr;
    
    int[] arr2 = new int[n];
    for (int i=0; i<n; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  }
}

Option 2 (using copyOf):

import java.util.Arrays;

class ZywOo {
  static int[] take(int[] arr, int n) {
    return n > arr.length ? arr : Arrays.copyOf(arr, n);
  }
}

Option 3 (using streams):

import java.util.Arrays;
public class ZywOo {
  public static int[] take(int[] arr, int n) {
     return Arrays.stream(arr).limit(n).toArray();
  }
}

Option 4 (using copyOfRange):

import java.util.Arrays;

public class ZywOo {
  public static int take(int[] arr, int n)[] {
    return Arrays.copyOfRange(arr, 0, Math.min(arr.length, n));
  }
}
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments