Part of array java

How to Split an Array in Java

Learn to split an array in Java using different ways. We will learn to split the array into equal parts, at the specified index and of equal lengths.

The copyOfRange() creates a new array of the same type as the original array, and contains the items of the specified range of the original array into a new array. Note that this method internally uses System.arraycopy() to copy the array items.

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

These are the method parameters.

  • original – the array from which a range is to be copied
  • from – the initial index of the range to be copied, inclusive
  • to – the final index of the range to be copied, exclusive. (This index may lie outside the array.)

An important point to note is that to index may lie outside the length of the array. Such index locations are filled with the default value of the type of array.

For example, for int , long and double types, the additional indices will be filled with zeros. For a boolean array, such indices will be filled with false and for object arrays, such positions will be filled with null.

It will throw IllegalArgumentException if from is bigger than to .

Читайте также:  Python filter none values

2. Splitting Array at Specified Index

Let’s say we are dividing an array in such a way that we should get two arrays of defined lengths. In such a case, we must use the copyOfRange() API to create two new arrays from the original array.

The first new array will be having the items starting from zero to the specified index, and the second new array will have items from the specified index to the end of the original array.

int[] original = ; int givenIndex = 3; splitArrayPart1 = Arrays.copyOfRange(original, 0, givenIndex); splitArrayPart2 = Arrays.copyOfRange(original, givenIndex, original.length); System.out.println(Arrays.toString(splitArrayPart1)); //[0, 1, 2] System.out.println(Arrays.toString(splitArrayPart2)); //[3, 4, 5, 6, 7, 8, 9]

2. Splitting Array in Two Equal Parts

Splitting the array in half is very much similar to the first example. We only have to find the split position ourselves and that is the middle of the array.

int[] original = ; int splitSize = original.length / 2; int[] splitArrayPart1 = Arrays.copyOfRange(original, 0, splitSize); int[] splitArrayPart2 = Arrays.copyOfRange(original, splitSize, original.length); System.out.println(Arrays.toString(splitArrayPart1)); //[0, 1, 2, 3, 4] System.out.println(Arrays.toString(splitArrayPart2)); //[5, 6, 7, 8, 9]

3. Splitting Array into N Parts

This is a bit tricky. Here we have to iterate over the array length but in chunks of a specified number. Then we have to use copyOfRange() method to create new array instances from those copied items.

We must keep special attention if there are remaining items after splitting the array equally. We need to create a new array of these remainder items.

For example, our original array contains 10 items. If we try to split the array in such a way that any new array must not contain more than 3 items. So in this case, there will be 4 arrays after the splitting procedure. 3 Arrays will have 3 items each, and 4th array will have only one item.

The given below is a method that does all the work described above.

public static List splitArray(T[] array, int splitSize) < int numberOfArrays = array.length / splitSize; int remainder = array.length % splitSize; int start = 0; int end = 0; Listlist = new ArrayList(); for (int i = 0; i < numberOfArrays; i++) < end += splitSize; list.add(Arrays.copyOfRange(array, start, end)); start = end; >if(remainder > 0) < list.add(Arrays.copyOfRange(array, start, (start + remainder))); >return list; >

Let us test this method with our original array and divide such that there must be at most 3 items in an array.

List arrayParts = splitArray(ArrayUtils.toObject(original), 3); for(Integer[] o: arrayParts) < System.out.println(Arrays.toString(o)); >//Output [0, 1, 2] [3, 4, 5] [6, 7, 8] [9]

In this tutorial, we learned to split an array in Java for different usecases. We learned to use the Arrays.copyOfRange() API to split the arrays into any number of parts.

There are other ways for array splitting as well, such that converting the array to List and the split the list. Such methods create unnecessary temporary variables without giving any clear advantage.

Источник

Part of array java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

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.

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; ireturn part; > public static void main(String args[])< int intArray[] = ; intArray = sliceArray(intArray, 3, 7); System.out.println(Arrays.toString(intArray)); > >

Output

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[] = ; intArray = Arrays.copyOfRange(intArray, 3, 7); System.out.println(Arrays.toString(intArray)); > >

Output

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 return part; > public static void main(String args[])< int intArray[] = ; intArray = sliceArray(intArray, 3, 7); System.out.println(Arrays.toString(intArray)); > >

Источник

Part of array java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью