Search code examples
javaarraysmethodsslicestride

How can I slice an int array by stride in Java?


I am learning Java.

In Python, I can:

my_list = [1,2,3,4]
my_new_list = my_list [::-1]
print my_new_list                # [4,3,2,1]

Is there any method I can use in Java to do that on int array?

Edit1: Sorry for the bad example. How about my_list [::-2]?

Edit2: What I mean my_list [::-2] is like

my_list = [1,2,3,4]
my_new_list = my_list [::-2]
print my_new_list                # [4,2]

Edit3: Slicing by stride in Python is to "check" the item in a list every step (stride).If the step is negative, Python would check the item from the end of the list to the beginning of the list. For example:

my_list = [1,2,3,4,5,6,7,8,9]
my_list1 = my_list[::2]       # my_list1 becomes [1,3,5,7,9]
my_list2 = my_list[::3]       # my_list2 becomes [1,4,7]
my_list3 = my_list[::4]       # my_list3 becomes [1,5,9]
my_list4 = my_list[::-3]      # my_list4 becomes [9,6,3]

Solution

  • Java does not have something builtin what you want, but you can built your own logic for it, something like this, just put the value in val , for example my_list[::2] 2 in this case val will be 2

    public static void main (String[] args) throws java.lang.Exception
    {
    int ml[] = {1,2,3,4,5,6,7,8,9};
    int val = -2;
    ArrayList al = new ArrayList();
    if(val>0){
    for(int i = 0 ; i<ml.length;i+=val){
        al.add(ml[i]);
    }
    }
    else if(val<0){
    for(int i = ml.length-1 ;  i>=0; i+=val){
        al.add(ml[i]);
    }   
    
    }
    
    
    for(int i = 0 ; i<al.size();i++){
        System.out.println(al.get(i));
    }
    
    }