java slice array code example

Example 1: array slice java

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

Example 2: lopp array java

For(<DataType of array/List><Temp variable name>   : <Array/List to be iterated>){
    System.out.println();
//Any other operation can be done with this temp variable.
}

Example 3: java list to array

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
    System.out.println(s);

Example 4: slicing array in java

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));
   }
}

Example 5: take a peice from array java

import java.util.IntStream;
// for java 8 and 8+
IntStream.range(start, end).map(x -> arr[x]).toArray();