59818

Java - Slice any array at steps

In python we are able to do the following:

array = [0,1,2,3,4,5,6,7,8,9,10] new_array= array[::3] print(new_array) >>>[0,3,6,9]

Is there an equivalent to this in Java? I have been looking for this type of array slicing, but I have had no luck. Any help would be great, Thanks!

Answer1:

If you are using Java 8, then you can make use of streams and do the following:

int [] a = new int [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // filter out all indices that evenly divide 3 int [] sliceArr = IntStream.range(0, a.length).filter(i -> i % 3 == 0) .map(i -> a[i]).toArray(); System.out.println(Arrays.toString(sliceArr));

<strong>Outputs</strong>: [0, 3, 6, 9]

Answer2:

There is a method in Arrays that might help.

int[] newArr = Arrays.copyOfRange(arr, 5,10);

It is obviously far less powerful the the python implementation.

Answer3:

Java has no built-in mechanism for this. You could write a helper function:

public static int[] sliceArray(int[] arr, int spacing) { int curr = 0; int[] newArr = new int[((arr.length - 1) / spacing) + 1]; for (int i = 0; i < newArr.length; ++i) { newArr[i] = arr[curr]; curr += spacing; } return newArr; }

Example

Note that Michael's answer is better (or at least less verbose) if you can utilize Java 8.

Recommend

  • How to get the sum from nested stream
  • How do I convert this program into java 8 functional style using streams?
  • Primitive stream vs object stream and actual boxing that occurs
  • Will inner parallel streams be processed fully in parallel before considering parallelizing outer st
  • How to add an integer unique id to query results - __efficiently__?
  • How to keep elements aligned regardless of browser zoom ratio?
  • how to convert a unix timestamp into nsdate in iphone [duplicate]
  • as3 addChild into a generated triangle
  • interpolation in 3d computer graphics
  • Broadcast advanced indexing numpy
  • Sql indexes vs full table scan
  • unescape special characters in ajax response data
  • C++ String tokenisation from 3D .obj files
  • touchstart in JavaScript no longer returns TouchList
  • Listview - list item selection and initial setting (custom made items)
  • C++ Armadillo Access Triangular Matrix Elements
  • How to use arithmetic operators with SAS macro variables [duplicate]
  • Retrieving a double from a JTextArea while solving for X
  • possible limitation of implode function in PHP
  • In C what exactly happens if i use () to initialize a double dimension array instead of the {}?
  • What Makes These Two Array Adds Different?
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Reading a file into a multidimensional array
  • App restarts from wrong activity
  • Excel's Macro-Recorder usage
  • Yii2: Config params vs. const/define
  • Jetty Server not starting: Unable to establish loopback connection
  • Spring security and special characters
  • How to handle AllServersUnavailable Exception
  • sending/ receiving email in Java
  • VBA Convert delimiter text file to Excel
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • retrieve vertices with no linked edge in arangodb
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?
  • Linking SubReports Without LinkChild/LinkMaster
  • python draw pie shapes with colour filled
  • Reading document lines to the user (python)
  • Python/Django TangoWithDjango Models and Databases