How to Get a slice of a primitive array in Java?


You can get a part of a Java array in between two specified indexes in various ways.

Copying contents − One way to do so is to create an empty array and copy the contents of the original array from the start index to the endIndex.

Example

 Live Demo

import java.util.Arrays;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

Output

[225, 56, 96, 3]

Using the copyOfRange() method − The copyOfRange() method of the java.util.Arrays class accepts an array, two integers representing start and end indexes and returns a slice of the given array which is in between the specified indexes.

Example

 Live Demo

import java.util.Arrays;
public class SlicingAnArray {
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = Arrays.copyOfRange(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

Output

[225, 56, 96, 3]

Example: Using Java8 stream

 Live Demo

import java.util.Arrays;
import java.util.stream.IntStream;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      IntStream stream = IntStream.range(startIndex, endIndex).map(i->array[i]);
      part = stream.toArray();
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
      }
   }

Output

[225, 56, 96, 3]
raja
Published on 06-Sep-2019 17:16:08
Advertisements