How can I print the values of a TreeMap?

1

This does not return anything to me: System.out.println(tree.values()); , castings do not work, i.e. System.out.println((int)tree.values());

How do I print the key values collection?

Map<Integer,String> tree=new TreeMap<>();
tree.values();//Devuelve una colección de los valores contenidos en 
//este mapa.
System.out.println(tree.values());
    
asked by Michelle 26.09.2017 в 04:23
source

2 answers

2

The values method of class TreeMap returns an object of type Collection so you can not print it that way unless you do a toString to collection : System.out.println(tree.values().toString())

To print a Collection , just go through it, you can use the foreach , in your case as the values are of type String , it would look like this:

for (String obj : tree.values()) {
   System.out.println(obj); // 
}

If what you want is to print the keys , you can use the tree.keySet() method that returns a Set that in the end also inherits from Collection so you can go through it in the same way:

for (Integer obj : tree.keySet()) {
   System.out.println(obj); // 
}
    
answered by 26.09.2017 / 07:03
source
2

As an addition to Ali's response, using Java 8:

// valores
tree.values().forEach(System.out::println);

// claves
tree.keySet().forEach(System.out::println);

// entradas
tree.entrySet().forEach(entry -> System.out.println("Clave: " + entry.getKey() + " -> Valor: " + entry.getValue()));
    
answered by 26.09.2017 в 09:46