我将保持简单: 我有一个名称的ArrayList,我必须删除某些包含特定字母的单词,但是我无法重新启动for循环。这就是我得到的:
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println("Start of List: " + wordList + "\n");
System.out.println("\nDrop: \"a\"");
someRandomFunction(wordList, "a");
System.out.println("wordList is now: " + wordList);
}
public static List<String> removeIfContains(List<String> strList, String removeIf){
List<String> tempList = new ArrayList<>(strList); // creating a copy
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(removeIf))
tempList.remove(i);
}
//Return will not work because of incompatible types.
}
已编译代码应为的示例:
ArrayList [你好,每个人,我,我,挣扎,在,计算机,科学]
删除以“ A”开头的单词:
新的ArrayList [您好,大家,我在奋斗中,在计算机,科学领域中
删除以“ I”开头的单词:
新的ArrayList [你好,每个人,我,奋斗中,计算机,科学]
我的代码的问题在于,在开始读取需要删除的新单词时,它不会使单词列表恢复到以前的状态。
答案 0 :(得分:1)
如果只想删除以某个字母开头的ArrayList
中的每个元素,则可以使用removeIf()
方法,该方法为:
删除此集合中满足给定谓词的所有元素。
wrodList.removeIf(e -> e.contains(thisLetter));
(需要Java 8 +)
听起来您想在每次删除元素后重置列表。为此,您可以创建副本ArrayList
进行检查,然后每次将其设置回原始副本:
List<String> copy = new ArrayList<>(wordList); //Creates a copy of wordList
答案 1 :(得分:1)
我相信这就是您想要的。我不确定是否要使用实例或静态方法。我相信您的问题是您没有创建副本。我注意到我在哪里创建副本。祝你好运。..我们都曾一度挣扎。
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println(removeIfContains(arrList, "H")); // calling the function and passing the list and what
System.out.println(removeIfContains(arrList, "I")); // I want to remove from the list
}
public static List<String> removeIfContains(List<String> strList, String removeIf){
List<String> tempList = new ArrayList<>(strList); // creating a copy
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(removeIf))
tempList.remove(i);
}
return tempList; // returning the copy
}