Pages

Remove an Element at specific index from an Array in Java

Remove an Element at a specific index from an Array in Java

  • We can remove a specific element from an array using index by using for loop, streams, etc.,.
Program for a Remove an Element at specific index from an Array in Java:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class removeNumber {

public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };

int index = 1;

int[] b = new int[arr.length - 1];

for (int i = 0, k = 0; i < arr.length; i++) {
if (i != index) {
b[k++] = arr[i];
}
}
for (int n : b) {
System.
out.print(n + " ");
}

System.out.println("\n<<------------------------------------>>");
int[] streamArr = {
5, 4, 3, 2, 1 };

int[] str = IntStream.
range(0, streamArr.length).filter(i -> i != index).map(i -> streamArr[i]).toArray();

for (int n : str) {
System.
out.print(n + " ");
}
System.out.println("\n<<------------------------------------>>");

int[] listArr = {
5, 4, 3, 2, 1, 6 };
List<Integer> arrayList = IntStream.of(listArr).boxed().collect(Collectors.toList());

arrayList.
remove(index);
System.
out.print(arrayList);
}
}
Output:
Remove element from array using index
Remove element from array using index

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.