Is it possible to access the element stored in ArrayDeque in each iteration ? Since ArrayDeque doesn't have the get method, its difficult for me to access each element. In the following example I have an integer arraydeque and i'm trying to retrieve the elements using an iterator and i want to check if the value is 2. If so i want to remove it from the ArrayDeque, but it gives me error.
import java.lang.*;
import java.util.*;
public class ArrayDequeTest {
public static void main(String[] args)
{
ArrayDeque<Integer> a = new ArrayDeque<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(2);
System.out.println("Elements added !!");
Iterator i = a.iterator();
System.out.println("\nRemoving the element whose value is 2");
while(i.hasNext())
{
if(i==2) // please suggest as to how i can compare
{
i.remove();
}
}
}
If you're using Java 8, you can make use of lambda expression and can get this removal operation done in just one line.
a.removeIf(e -> e == 2);