Delete all the elements of a treeMap

1

I would like to know how to remove all the elements of a list treeMap of Java. I have the following method that removes only one element:

public boolean eliminarProducte(String codi){
     return map_catalogo.remove(codi)!=null;
}
    
asked by FranEET 11.01.2017 в 23:13
source

2 answers

5

Like all other Java collections, if you want to delete all the elements, simply call the method clear() .

map_catalogo.clear();
    
answered by 11.01.2017 / 23:16
source
4

You must use the clear () method that removes all assignments from this TreeMap .

Example:

  TreeMap<String, String> treemap = new TreeMap<String, String>();           
   treemap.put("2", "doi");
   treemap.put("1", "unu");
   treemap.put("3", "trei");
   treemap.put("6", "sase");
   treemap.put("5", "cinci");       

   //Elimina todos los elementos.      
   treemap.clear();

   System.out.println("TreeMap ¿esta vacio?: "+treemap.isEmpty());

The result is:

TreeMap ¿esta vacio?: true

The method you use, remove () removes only the assignment for a key within TreeMap (if present).

Example:

   TreeMap<String, String> treemap = new TreeMap<String, String>();           
   treemap.put("2", "doi");
   treemap.put("1", "unu");
   treemap.put("3", "trei");
   treemap.put("6", "sase");
   treemap.put("5", "cinci");      
   System.out.println("Remueve valor con key 6: "+treemap.remove("6"));

The result is:

Remueve valor con key 6: sase

This would be a method that you would use, which would indicate if all the elements within the TreeMap were successfully removed:

public void eliminarProductos(){
     map_catalogo.clear()
}
    
answered by 11.01.2017 в 23:36