ViniV
ViniV

Reputation: 39

Delete a certain object from an ArrayList java

I have an ArrayList on Java to store several orders from a factory. These orders have several attributes, amongst them is idPedido. Thing is, if I declare orders 1, 2 and 3, delete order 2 via a method called bajaPedido (Shown below):

public void bajaPedido(){
     try{
              idPedido=teclado.nextInt();
              listaPedidos.remove(idPedido); 
           }catch(InputMismatchException e){
               teclado.next();
              System.out.print("Debe utilizar números, por favor, repita el proceso");
           }catch(IndexOutOfBoundsException e){
               teclado.next();
               System.out.println("No existe un pedido con ese ID");
            }
    }

then the 3rd order will be on the second place of the array, because idPedido in this situation refers to the position of the array, not to the variable stored inside the object.

Question is, how could I code it in a way that if I type in the id it will search up which object contains such id and removes it, instead of removing the position the id equals to?

Upvotes: 1

Views: 106

Answers (3)

Vaibhav
Vaibhav

Reputation: 31

You can solve this by using stream api

List<Orders> orders= contain orders object
orders.stream().filter(item -> item.getIdPedido().equals("Your Id")).findFirst()
            .map(p -> {
                orders.remove(p);
                return p;
            }).get();

I hope it may work.

Upvotes: 1

Jordi
Jordi

Reputation: 387

I think the easiest approch would be to use a Map instead of a list, where the key should be your "idPedido" and value the "pedido object".

Map<Integer, Pedido> map = new HashMap<>();
map.put(idPedido, Pedido);
map.remove(idPedido);

If you want to still use a List, you should remove "Pedido" objects from your "listaPedidos" with this method from list interface in orther to be not bounded to your list index.

boolean remove(Object o)

In that case you will have to implement "equals" method on your Pedido class.

https://docs.oracle.com/javase/8/docs/api/java/util/List.html#remove-java.lang.Object-

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Use Iterator as shown below:

idPedido = teclado.nextInt();
for(Iterator<Order> itr = listaPedidos.iterator(); itr.hasNext();){
    Order order = itr.next();
    if(order.getId() == idPedido){
        itr.remove();
    }
}

If the id of all the orders in listaPedidos are unique, use break; after itr.remove(); for a better performance (i.e. to prevent the loop running even after removing the desired order).

Upvotes: 1

Related Questions