如何从数组或列表中删除两个连续的元素?
我有一个阵列:
new String[]{"FIRST", "SECOND", "SECOND", "THIRD", "FOURTH", "FIRST", "FOURTH"})
我应该从这个数组中删除两个连续的元素。
要删除的元素:" FIRST"," SECOND"
删除元素后,新数组或列表应如下所示:
new String[]{"SECOND", "FIRST", "FOURTH", "FIRST", "FOURTH"})
现在我已经:" SECOND"," FIRST"
结果:new String[]{"FOURTH", "FIRST", "FOURTH"})
这是我的代码:
String[] s1 = new String[arr.length];
String n = "FIRST";
String s = "SECOND";
String w = "THIRD";
String e = "FOURTH";
//I found two successive elements, and element next to them
//My question is, how can I remove these element from list,
or copy array without these elements to a new array?
for (int i = 0; i <arr.length ; i++) {
if (arr[i].equals(n) && arr[i + 1].equals(s)){
System.out.println(arr[i + 2]);
}
}
如何从数组或列表中删除两个连续的元素?
答案 0 :(得分:2)
public static void main(String[] args) {
String[] arr = new String[]{"FIRST", "SECOND", "SECOND", "THIRD", "FOURTH", "FIRST", "FOURTH"};
String[] toRemove = new String[]{"FIRST","SECOND"};
arr=removeSuccessive(arr,toRemove);
System.out.println(Arrays.toString(arr));
}
private static String[] removeSuccessive(String[] arr, String[] toRemove) {
ArrayList<String> res=new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if(!arr[i].equals(toRemove[0]))
res.add(arr[i]);
else if(i+1<arr.length && !arr[i+1].equals(toRemove[1]))
res.add(arr[i]);
else
i++;
}
return res.toArray(new String[res.size()]);
}
您可以在此处检查并运行此代码: https://ideone.com/v6nPRf
答案 1 :(得分:0)
您可以为此使用 regexp。将每个数组连接成一个带有一些分隔符 ⦀
和 replace
的字符串:
String[] arr1 = {"FIRST", "SECOND", "SECOND", "THIRD", "FOURTH",
"FIRST", "SECOND", "FIRST", "SECOND", "FIRST", "FOURTH"};
String[] arr2 = {"FIRST", "SECOND"};
// join each array into a single
// string with delimiter characters
String str1 = String.join("\u2980", arr1);
String str2 = String.join("\u2980", arr2);
String[] removed = Arrays
.stream(str1
// replace all occurrences of the second string
// in the first string with delimiter characters
.replaceAll(str2, "\u2980")
// split a string around delimiter characters
.split("\u2980"))
// remove empty strings
.filter(str -> str.length() > 0)
.toArray(String[]::new);
System.out.println(Arrays.toString(removed));
// [SECOND, THIRD, FOURTH, FIRST, FOURTH]
答案 2 :(得分:-1)
package com.sash;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SashStream {
public static void main(String[] args) {
String[] test = new String[] { "FIRST", "SECOND", "SECOND", "FIRST", "FOURTH", "FIRST", "FOURTH" };
String[] out1 = filter(test, "FIRST", "SECOND");
String[] out2 = filter(out1, "SECOND", "FIRST");
System.out.println(Arrays.toString(out2));
}
private static String[] filter(String[] test, String first, String last) {
List<String> outputList = new ArrayList<>();
for (int i = 0; i < test.length; i++) {
if((test.length-1)!=i && test[i].equals(first) && test[i+1].equals(last)){
i++;
} else {
outputList.add(test[i]);
}
}
return outputList.toArray(new String[0]);
}
}
输出是:
[FOURTH, FIRST, FOURTH]