×

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] = {1, 5, 3, 2, 7, 12, 4, 11}

Now we need to locate a slice of a array index between a[4] and a[7]. Where a[4] represents the startIndex and a[7] represents the endIndex. As a result, we have the below sliced array:a[] = {7, 12, 4, 11}

In this section, we'll look at how to use Java to find a slice of an array. There are three methods for locating a slice of an array:

  • By duplicating elements
  • Using the copyOfRange() Method
  • Using Java 8 Stream

Let's go over each method in depth:

Elements Copying Method:

It is a native technique for obtaining an array slice. In this technique, we first determine the beginning and ending indexes of the provided array. Then we make an empty array (sliced array) of size (endIndex - startIndex). Copies the elements (from startIndex) from the provided array to the sliced array. Finally, output the sliced array. Let's put the aforesaid method into action in a Java programme to get a sliced array of the given array. This is a program. An array of primitive types will be used.

SliceArrayExample:

import java.util.Arrays;   
public class SliceArrExample  
{   
public static int[] getSlice(int[] arr, int a, int b)   
{   
int[] slicedArr= new int[b - a];   
for (int i = 0; i < slicedArr.len; i++)   
{   
slicedArr[i] = array[a + i];   
}   
return slicedArr;   
}   
public static void main(String args[])   
{   
int[] arr= {1, 5, 8, 2, 4, 9, 6, 11, 0, 3};   
int a= 4, b = 7;   
int[] slicedArr= getSlice(arr, a, b + 1);   
System.out.println("Slice of Arr: "+Arrays.toStr(slicedArr));   
}   
}  

Output:

Slice of Arr: [4, 9, 6, 11]

Using the copyOfRange() Function:

The copyOfRange() method is a member of the Java Arrays class. It replicates the array's specified range to the newly formed array (slice array) and provides the newly produced array containing the array's specified range from the original array. The slicing of an array takes O(n) time and O(n) space to contain elements, where n represents the number of elements in the new array.

Syntax:

public static int[] copyOfRange(int[] original, int from, int to)

The method parses the following three parameters:

  • original: It is an array whose slice must be discovered.
  • It is the starting index. It must be in the range of 0 to the length of the provided array.
  • It is the final index.

The following exceptions are thrown:

  • If from is less than 0 or higher than the length of the provided array, an ArrayIndexOutOfBoundsException is thrown.
  • If the parameter from is bigger than the parameter to, an IllegalArgumentException is thrown.
  • If the provided array is null, a NullPointerException is thrown.

SliceArrayExample1:

import java.util.Arrays;   
public class SliceArrExample1 
{   
public static int[] slice(int[] arr, int a, int b)   
{   
int[] slicedArr = Arrays.copyOfRange(arr, a, b);   
return slicedArr;   
}   
public static void main(String args[])   
{   
//getting array, a and b   
int[] arr= {1, 2, 6, 9, 11, 8, 5, 4, 3};   
int a= 1, b = 5;   
int[] sliceArr= slice(arr, a, b+ 1);   
System.out.println("Slice of Arr: "+Arrays.toStr(sliceArr));   
}   
}   

Output:

Slice of Arr: [2, 6, 9,11, 8]

Using the Java 8 Stream:

We may use the Java 8 Stream to find the slicing of an array by following the instructions below.

  • Find the startIndex and endIndex arrays first.
  • Using the range() technique, convert the elements in range into Primitive Stream.
  • Map the requested elements from the supplied array using the map() function.
  • Convert the mapped array to an array by calling the toArray() function.
  • Please print the sliced.

SliceArrayExample2:

import java.util.Arrays;   
import java.util.stream.IntStream;   
public class SliceArrayExample2 
{   
public static int[] findSl(int[] array, int startIndex, int endIndex)   
{   
int[] slcarray = IntStream.range(a, e).map(i -> array[i]).toArr();   
return slcarray;   
}   
//main() method  
public static void main(String args[])   
{   
//Get the array, a and b
int[] array = {2, 5, 9, 5, 4, 10, 3, 8, 7, 12, 0, 9};   
int a= 4, b = 8;   
int[] slcarr = findS(array, a, b + 1);   
//Printing  the slice of the array   
System.out.println("Array for the specified range is: "+Arrays.toStr(slcarr));   
}   
}  

Output:

 Array for the specified range is: [4,10, 3, 8, 7]

Related Topics

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.