
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
By 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
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]
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]
Advertisements