IMBABOT :
Got a List of elements:
String[] temp = new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(temp));
need to remove elements "EAST" and "WEST" if they consecutive:
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).equals("EAST") && list.get(i + 1).equals("WEST")) {
list.remove(i);
list.remove(i + 1);
}
}
After this code, list contains:
[NORTH, SOUTH, SOUTH, WEST, WEST]
I need:
[NORTH, SOUTH, SOUTH, NORTH, WEST]
How to remove consecutive elements from list?
Arvind Kumar Avinash :
Do it as follows:
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).equals("EAST") && list.get(i + 1).equals("WEST")) {
list.remove(i);
list.remove(i);
}
}
System.out.println(list);
Output:
[NORTH, SOUTH, SOUTH, NORTH, WEST]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=299773&siteId=1