Open In App

How to get slice of a Primitive Array in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Given a Primitive Array, the task is to get a Slice of this array in Java, using start and ending index. Examples:

Input: arr[] = {1, 2, 3, 4, 5}, startIndex = 2, endIndex = 4
Output: {3, 4, 5}

Input: arr[] = {1, 2, 3, 4, 5}, startIndex = 0, endIndex = 1
Output: {1, 2}
  • Method 1: Naive Method.
    1. Get the Array and the startIndex and the endIndex.
    2. Create and empty primitive array of size endIndex-startIndex.
    3. Copy the elements from startIndex to endIndex from the original array to the slice array.
    4. Return or print the slice of the array.

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
 
import java.util.Arrays;
 
class GFG {
    // Function to get slice of a primitive array in Java
    public static int[] getSliceOfArray(int[] arr,
                                        int start, int end)
    {
 
        // Get the slice of the Array
        int[] slice = new int[end - start];
 
        // Copy elements of arr to slice
        for (int i = 0; i < slice.length; i++) {
            slice[i] = arr[start + i];
        }
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, end = 4;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, end + 1);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}


Output

[3, 4, 5]
  • Method 2: Using Arrays.copyOfRange() method.
    1. Get the Array and the startIndex and the endIndex.
    2. Get the slice using Arrays.copyOfRange() method.
    3. Return or print the slice of the array.

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
 
import java.util.Arrays;
 
class GFG {
    // Function to get slice of a primitive array in Java
    public static int[] getSliceOfArray(int[] arr,
                                        int startIndex,
                                        int endIndex)
    {
 
        // Get the slice of the Array
        int[] slice
            = Arrays.copyOfRange(arr, startIndex, endIndex);
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, end = 4;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, end + 1);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}


Output

[3, 4, 5]
  • Method 3: Using Java 8 Streams
    1. Get the Array and the startIndex and the endIndex.
    2. Convert the specified range of elements from the startIndex to endIndex to Primitive Stream using range() method.
    3. Map the specified elements from the original array using map() method.
    4. Convert the mapped array into array using toArray() method.
    5. Return or print the slice of the array.

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
 
import java.util.Arrays;
import java.util.stream.IntStream;
 
class GFG {
 
    // Function to get slice of a primitive array in Java
    public static int[] getSliceOfArray(int[] arr,
                                        int startIndex,
                                        int endIndex)
    {
 
        // Get the slice of the Array
        int[] slice = IntStream
 
                          // Convert the specified elements
                          // of array into IntStream
                          .range(startIndex, endIndex)
 
                          // Lambda expression to get
                          // the elements of IntStream
                          .map(i -> arr[i])
 
                          // Convert the mapped elements
                          // into the slice array
                          .toArray();
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, end = 4;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, end + 1);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}


Output

[3, 4, 5]
  • Method 4: Using System.arraycopy() method.
    1. Get the Source Array, its startIndex and total no. of components to be copied
    2. Get the Destination Array and its startIndex
    3. Get the slice using System.arraycopy() method.
    4. Return or print the slice of the array.

Syntax:

public static void arraycopy(Object source_arr, int sourcePos, Object dest_arr, int destPos, int len)

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
// Using System.arraycopy()
 
import java.util.Arrays;
import java.util.stream.IntStream;
 
class GFG {
 
    // Function to get slice of a primitive array in Java
    public static int[] getSliceOfArray(int[] arr,
                                        int startIndex,
                                        int len)
    {
 
        // Get the slice of the Array
        int[] slice = new int[len];
 
        // Slice the original array
        System.arraycopy(arr, startIndex, slice, 0,
                         len); // [3, 4, 5]
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, len = 3;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, len);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

[3, 4, 5]
  • Method 5: Using List.subList() method.
    1. Get the Source Array, its startIndex and endIndex to be copied
    2. Convert the Source Array to ArrayList
    3. Get the slice using List.subList() method
    4. Again Convert the Sliced ArrayList to Sliced Array
    5. Return or print the slice of the array.

Syntax:

public List subList(int fromIndex, int toIndex)

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
// Using List.subList()
 
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
class GFG {
      // Function to get slice of a primitive array in Java
      static int[] getSliceOfArray(int[] arr, int fromIndex, int toIndex){
           
          // Conversion of Array To ArrayList
          List<Integer> ar = Arrays.stream(arr).boxed().collect(Collectors.toList());
           
          // Get the slice of the Original Array
          List<Integer> arrl = ar.subList(fromIndex, toIndex);
           
          // Conversion of ArrayList to Array
          int[] slice = arrl.stream().mapToInt(i -> i).toArray();
       
          // return the slice
        return slice;
    }
    public static void main (String[] args) {
           
          // Get the array, startIndex and endIndex
          int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, end = 5;
           
          // Get the slice of the array
          int[] slice = getSliceOfArray(arr, start, end);
           
          // Print the slice of the array
          System.out.println(Arrays.toString(slice));
    }
}
 
// This code is contributed by Susobhan AKhuli


Output

[3, 4, 5]
  • Method 6: Using Streams API:
    1. Get the Source Array, its startIndex and total no. of components to be copied
    2. Get the slice using stream method
    3. Return or print the slice of the array.

Syntax:

int[] sliced = Arrays.stream(original)
                      .skip(startIndex)
                      .limit(length)
                      .toArray();

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
// Using Stream API
 
import java.util.Arrays;
import java.util.stream.Collectors;
 
class GFG {
    // Function to get slice of a primitive array in Java
    static int[] getSliceOfArray(int[] arr, int startIndex,
                                 int len)
    {
 
        // Get the slice of the array
        int[] slice = Arrays.stream(arr)
                          .skip(startIndex)
                          .limit(len)
                          .toArray();
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, len = 3;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, len);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}
 
// This code is contributed by Susobhan AKhuli


Output

[3, 4, 5]
  • Method 7: Using ArrayUtils.subarray() Method:
    1. Get the Source Array, its startIndex and endIndex to be copied
    2. Get the slice using ArrayUtils.subarray() method
    3. Return or print the slice of the array.

Syntax:

int[] sliced = ArrayUtils.subarray(Original_array, Start_Index, End_Index);

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
// Using ArrayUtils.subarray() Method
 
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
 
class GFG {
    // Function to get slice of a primitive array in Java
    static int[] getSliceOfArray(int[] arr, int startIndex, int endIndex)
    {
 
        // Get the slice of the array
        int[] slice = ArrayUtils.subarray(arr, startIndex, endIndex);
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and endIndex
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, end = 5;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, end);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}
 
// This code is contributed by Susobhan AKhuli


Output

[3, 4, 5]
  • Method 8: Using Guava library:
  1. Get the Source Array, its startIndex  and length to be copied
  2. Convert array to list
  3. Get the slice using Guava library
  4. convert list to array again
  5. Return or print the slice of the array.

Syntax:

List<Integer> subList = list.subList(startIndex, startIndex + length);

Below is the implementation of the above approach:

Java




// Java program to Get a Slice
// of a Primitive Array
// Using Guava library
 
import com.google.common.primitives.Ints;
import java.util.Arrays;
import java.util.List;
 
class GFG {
    // Function to get slice of a primitive array in Java
    static int[] getSliceOfArray(int[] arr, int startIndex,
                                 int length)
    {
 
        // convert array to list
        List<Integer> list = Ints.asList(arr);
           
          // Get the slice of the list
        List<Integer> subList
            = list.subList(startIndex, startIndex + length);
           
          // convert list to array
        int[] slice = Ints.toArray(subList);
 
        // return the slice
        return slice;
    }
    public static void main(String[] args)
    {
 
        // Get the array, startIndex and length of sliced
        // array
        int[] arr = { 1, 2, 3, 4, 5 };
        int start = 2, len = 3;
 
        // Get the slice of the array
        int[] slice = getSliceOfArray(arr, start, len);
 
        // Print the slice of the array
        System.out.println(Arrays.toString(slice));
    }
}
 
// This code is contributed by Susobhan AKhuli


Output

[3, 4, 5]


Last Updated : 01 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads