我正在尝试删除以r和g开头的列表元素
一个条件可以很好地删除从r开始的elememts,但是下一个在if循环中不起作用的条件可以帮助我弄错我的地方。谢谢.. !!
我的代码是
import java.util.Arrays;
import java.util.LinkedList;
public class EasyRemovingList {
void removeList(){
String[] inpArray={"red","green","blue","ivory"};
LinkedList<String> upList = new LinkedList<String>(Arrays.asList(inpArray));
System.out.println("Actual "+upList+" "+upList.size());
//System.out.println(upList.get(3));
for(int i = 0;i<upList.size();i++){
//System.out.println(upList.get(i));
if(upList.get(i).startsWith("r")||upList.get(i).startsWith("g")){
upList.remove(i);
System.out.println("Updated "+upList);
}
}
//System.out.println(upList);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
EasyRemovingList er = new EasyRemovingList();
er.removeList();
}
}
输出为
Actual [red, green, blue, ivory] 4
Updated [green, blue, ivory]
预期输出为
Actual [red, green, blue, ivory] 4
Updated [blue, ivory]
答案 0 :(得分:2)
尝试使用removeIf()
。
upList.removeIf(element -> {return element.starts("r") || element.startsWith("g");});
MVCE
import java.util.Arrays;
import java.util.LinkedList;
/**
*
* @author Sedrick
*/
public class JavaApplication4 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String[] inpArray={"red","green","blue","ivory"};
LinkedList<String> upList = new LinkedList(Arrays.asList(inpArray));
System.out.println("Actual "+upList+" "+upList.size());
upList.removeIf(element -> {
return element.startsWith("r") || element.startsWith("g"); //To change body of generated lambdas, choose Tools | Templates.
});
System.out.println("Actual "+upList+" "+upList.size());
}
}
结果
run:
Actual [red, green, blue, ivory] 4
Actual [blue, ivory] 2
BUILD SUCCESSFUL (total time: 0 seconds)
答案 1 :(得分:2)
您正在移动时正在移走,这在编码中是一种难闻的气味。
您可以尝试使用 iterator 进行删除。
通过iterator
,您可以将其用作
while(iter.hasNext()) {
String s = iter.next();
if (s. startsWith(“r”) || s. startsWith(“g”)) {
iter.remove();
}
}
答案 2 :(得分:1)
当您删除一个元素时,所有其他元素都将移过来,您将跳过下一个元素。为了避免这种情况,只需从1减去LinkedList
的长度开始,然后循环直到i
等于零:
for(int i = upList.size()-1;i>=0;i--){
if(upList.get(i).startsWith("r")||upList.get(i).startsWith("g")){
upList.remove(i);
}
}
System.out.println("Updated "+upList);
}
输出:
Actual [red, green, blue, ivory] 4
Updated [blue, ivory]
答案 3 :(得分:0)
您可以使用Java 8作为简单的解决方案:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StackOverFlow {
public static void main(String[] args) {
String[] inpArray = { "red", "green", "blue", "ivory" };
LinkedList<String> upList = new LinkedList<String>(Arrays.asList(inpArray));
System.out.println("Actual " + upList + " " + upList.size());
Predicate<String> p = e -> e.startsWith("r") || e.startsWith("g");
// Return a new list
System.out.println(upList.stream().filter(p.negate()).collect(Collectors.toList()));
// Updates your existing list
upList.removeIf(p);
System.out.println(upList);
}
}