Close

## Shifting Elements in an Array Java

Last Updated on Wednesday 5th Oct 2022

## Shift Array Java

• The `skip(n)` method is that first n elements of a stream.The `n` parameter can't be negative, and if it's higher than the size of the stream, `skip()` returns an empty stream.

### Java Shift Array

```			```
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = {
1,
2,
3,
4,
5,
6,
7
};
Arrays.stream(array).skip(1).forEach(System.out::println);
}
}

```

```
```			```
2
3
4
5
6
7

```

```

### How to Shift Elements in an Array

Use the `Collections.rotate(List<type> list, int distance)` to Shift

```			```
Collections.rotate(list.subList(j, k+1), -1);

```

```
• Rotates the elements in the specified list by the specified distance.
• After calling this method, the element at index `i` will be the element previously at index `(i - distance)` mod `list.size()`, for all values of i between 0 and `list.size()-1`, inclusive.
```			```
public static void rotate(List<?> list, int distance)

```

```

Parameters

• `list` - the list to be rotated.
• `distance` - the distance to rotate the list. There are no constraints on this value,it may be zero, negative, or greater than `list.size()`.
```			```
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String args[]) {
String[] strArr = {
"Alice",
"Benny",
"Dan",
"Sam"
};
System.out.println("List : " + Arrays.toString(strArr));

List < String > list = Arrays.asList(strArr);
Collections.rotate(list, 2);

System.out.println("After: " + list);

}
}

```

```
```			```
// List : [Adam, Alice, Benny, Dan, Sam]
// After : [Dan, Sam, Adam, Alice, Benny]

```

```