How can I slice an int array in steps 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 that I can use in Java to do this in an int array?

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

Edit2: I mean that my_list [:: - 2] is similar to

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

Edit3: Slicing step by step in Python is to "check" an element in the list at each step (step). If the step is negative, Python will 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]
+4
source share
5 answers

Java - , , , - , val, my_list [:: 2] 2 val 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));
}

}
+1

, Collections.reverse() .

Integer a[]={1,2,3,4};
List <Integer> list = Arrays.asList(a);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);

DEMO

+4

, Collections#reverse . List , .

public class Test {

    public static void main(String[] args) {
        Integer[] arr = new Integer[] { 1, 2, 3, 4 };
        List<Integer> list = Arrays.asList(arr);
        Collections.reverse(list);
        arr = list.toArray(new Integer[list.size()]);
        System.out.println(Arrays.toString(arr));
    }

}

OUTPUT

[4, 3, 2, 1]
+1

Java 8

int a = { 1, 2, 3, 4 };
int step = -2;

int b = IntStream.range(0, a.length)
            .filter(i -> i%step == 0)
            .map(i -> a[(step < 0) ? a.length-i-1 : i])
            .toArray();

.

+1

Apache Commons Lang :

ArrayUtils.reverse(int[] array)
0

Source: https://habr.com/ru/post/1622075/


All Articles