我需要在每次出现特定元素之前添加一个元素。我可以使用 for 循环执行此操作并计算索引,然后添加元素。有没有不使用 for 循环或使用流的有效方法。
例如:在每次出现 2 之前int[] a = {1,2,4,5,7,9,2,5}
添加元素{3},导致{1,3,2,4,5,7,9,3,2,5}
试图:
int[] a = {1, 2, 4, 5, 7, 9, 2, 5};
int[] new1 = null;
int[] indexToAdd = IntStream.range(0, a.length)
.filter(i -> a[i] == 2)
.map(i -> i)
.toArray();
for(int j = 0; j<indexToAdd.length; j++){
final Integer innerj = new Integer(j);
new1 = IntStream.range(0,a.length)
.map(i -> {
if (i < indexToAdd[innerj]) {
return a[i];
} else if (i == indexToAdd[innerj]) {
return 3 …Run Code Online (Sandbox Code Playgroud)