Skip to content

Commit a16d961

Browse files
authored
[BAEL-9396] Add Samples (#18715)
1 parent f1c7028 commit a16d961

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.array.remove;
2+
3+
import java.util.stream.IntStream;
4+
5+
public class RemoveElementFromArrayNativeJava {
6+
static int[] removeWithLoop(int[] source, int index) {
7+
int[] result = new int[source.length - 1];
8+
for (int i = 0, j = 0; i < source.length; i++) {
9+
if (i == index) {
10+
continue; // skip the element we are removing
11+
}
12+
result[j++] = source[i];
13+
}
14+
return result;
15+
}
16+
17+
static int[] removeWithArrayCopy(int[] source, int index) {
18+
int elementsBefore = index;
19+
int elementsAfter = source.length - index - 1;
20+
int[] result = new int[source.length - 1];
21+
System.arraycopy(source, 0, result, 0, elementsBefore);
22+
System.arraycopy(source, index + 1, result, index, elementsAfter);
23+
return result;
24+
}
25+
26+
static int[] removeWithStream(int[] source, int index) {
27+
return IntStream.range(0, source.length)
28+
.filter(i -> i != index)
29+
.map(i -> source[i])
30+
.toArray();
31+
}
32+
}

0 commit comments

Comments
 (0)