Java map вывести только значения

Printing HashMap In Java

It doesn’t seem to work. What is the problem? EDIT: Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?

I recommend you become familiar with Java’s documentation (it will answer many of your questions). For example, this is the documentation for Map ‘s size() method: «Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE .»

Your code is looking for Values in Keys — which is not correct. Either look for key in Keys or value in Values

If it has 1 key / value it will ofcourse have size 1. But this does not have anything to do with zero-based indexing.

This is a good question. But there is an answer here provided here that can do this in one line, if you see Mingfei’s solution.

17 Answers 17

keySet() only returns a set of keys from your hash map, you should iterate this key set and the get the value from the hash map using these keys.

Читайте также:  Админ-панель

In your example, the type of the hash map’s key is TypeKey , but you specified TypeValue in your generic for-loop , so it cannot be compiled. You should change it to:

for (TypeKey name: example.keySet())
example.forEach((key, value) -> System.out.println(key + " " + value)); 

If you don’t require to print key value and just need the hash map value, you can use others’ suggestions.

Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?

The collection returned from keySet() is a Set . You cannot get the value from a set using an index, so it is not a question of whether it is zero-based or one-based. If your hash map has one key, the keySet() returned will have one entry inside, and its size will be 1.

A simple way to see the key value pairs:

Map map = new HashMap<>(); map.put("a", 1); map.put("b", 2); System.out.println(Arrays.asList(map)); // method 1 System.out.println(Collections.singletonList(map)); // method 2 

Both method 1 and method 2 output this:

Thats true. the NPE always lurks in such short cuts. I only wanted to show a similar out put.. I think especially when you’re debugging to a log/console and you just wana peek into a map whose data you know isnt null. this is a quick fire! But if its code checking from scratch. then you’re right, its tricky and in good programming context, it should be avoided!

Assuming you have a Map , you can print it like this:

for (Map.Entry entry : map.entrySet())

To print both key and value, use the following:

for (Object objectName : example.keySet())
  • Get map.values() , which gets the values, not the keys
  • Get the map.entrySet() which has both
  • Get the keySet() and for each key call map.get(key)

For me this simple one line worked well:

Arrays.toString(map.entrySet().toArray()) 
map.forEach((key, value) -> System.out.println(key + " " + value)); 

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.

A simple print statement with the variable name which contains the reference of the Hash Map would do :

HashMap HM = new HashMap<>(); //empty System.out.println(HM); //prints key value pairs enclosed in <> 

This works because the toString() method is already over-ridden in the AbstractMap class which is extended by the HashMap Class More information from the documentation

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map’s entrySet view’s iterator, enclosed in braces («<>«). Adjacent mappings are separated by the characters «, » (comma and space). Each key-value mapping is rendered as the key followed by an equals sign (» mt24″>

Источник

Распечатайте все ключи и значения с карты в Java

В этом посте будут обсуждаться различные методы вывода всех ключей и значений из карты в Java.

Похожие сообщения:

Мы знаем, что keySet() метод возвращает установленное представление ключей, содержащихся в карте, и values() метод возвращает установленное представление значений, содержащихся в карте. Итак, мы можем использовать keySet() распечатать все ключи, присутствующие на карте, и values() для печати всех значений. Есть несколько способов сделать это:

1. Использование Iterator

Map не имеет собственного итератора, поскольку он не расширяет Collection интерфейс. Оба keySet() а также values() возвращает набор, а набор расширяет Collection интерфейс, мы можем получить итератор.

2. Для каждого цикла

Цикл For-each доступен для любого объекта, реализующего Iterable интерфейс. В качестве Set расширяет Iterable интерфейс, мы можем использовать цикл for-each для перебора набора ключей и значений.

3. Java 8 — Iterator.forEachRemaining()

The Iterator интерфейс обеспечивает forEachRemaining() метод, который может печатать каждый элемент, пока все элементы не будут обработаны.

4. Java 8 – Stream.forEach()

Мы можем использовать цикл по набору ключей и значениям, используя Stream.forEach() метод для печати каждого элемента потока.

5. Использование toString()

Для отображения всех ключей или значений, присутствующих на карте, мы можем просто напечатать строковое представление keySet() а также values() , соответственно.

Ниже приведена простая программа на Java, которая печатает все ключи карты, используя keySet() в Java:

Источник

Use entrySet() (or values() if that’s what you need) instead of keySet() :

Map missions = new HashMap<>(); missions.put("name", 1.0); missions.put("name1", 2.0); missions.entrySet().stream().forEach(e-> System.out.println(e)); 

You could pass the method reference directely instead of creating a lambda: forEach(System.out::println) . However, it’s just a matter of style.

Yes but in this case I am not sure if what OP wants is value or entry — if it’s the latter, then lambda would be a better choice (as you may want to get key or value from an Entry ).

@ΔλЛ IDK, keys => keySet() , values => values() , both => entrySet() ; doesn’t affect the forEach . But as I said, it’s a style thing—just wanted to mention it.

HashMap missions = new HashMap<>(); missions.put("name", 1.0); missions.put("name1", 2.0); missions.entrySet().forEach(System.out::println); 

100% agree with you. What I thought was, since question is already answered, my answer will help to a person who is looking for a solution can easily locate the answer. But I do agree with you which I learnt something from you, thanks.

// Stores the values in a list which can later used missions.values().stream().collect(Collectors.toList()); 
//print it to standard op missions.values().forEach(val -> System.out.println(val)); 

Please read How to Answer and refrain from answering code-only. Instead, remember you are not only answering the OP, but also to any future readers (especially when answering 3 year old question). Thus, please edit the answer to contain an explanation as to why this code works.

Источник

Java Print HashMap Example

This example shows how to print HashMap in Java. The example also shows how to print all keys, all values, and all key-value pairs of HashMap using different ways.

How to print HashMap in Java?

The AbstractMap class, the parent class of the HashMap class, has overridden the toString method which returns a string representation of the map. All key-value pairs are enclosed in < and >and separated by a comma (,). The iterator of the entry set returns the order of the key-value pairs.

How to print all keys and values of HashMap using entrySet?

If you do not want the default formatting done by the toString method, you can get the entry set from the HashMap and print all key-value pairs one by one using the for loop as given below.

Java 8 and above

If you are using Java version 8 and above, you can use the below given code to print all keys and values of HashMap.

How to print all the keys of HashMap?

The keySet method of the HashMap class returns a Set view containing all the keys of the HashMap.

You can also use the System.out.println statement instead of using the for loop if you do not want to change the output format.

How to print all the values of the HashMap?

The values method of the HashMap returns a Collection view containing all the values contained in the HashMap.

You can also use System.out.println statement instead of using the for loop if you do not want to change the output format.

How to print HashMap containing custom class object as keys or values?

In all of the above examples, we printed Integer and String objects using the System.out.println statement. They were printed fine because both of these classes have overridden the toString method. Let’s try to print HashMap containing custom class objects.

We have put objects of Emp class as values in the HashMap in below given example.

As you can see from the output, the keys were printed fine but the values were not. It is because our Emp class has not overridden the toString method so it inherited the method from the Object class.

The toString method of the Object class returns the class name of the object, followed by @, followed by the hexadecimal hash code of the object. The format is not readable and hence it is suggested for all the subclasses to override the toString method to produce informative text.

Let’s override the toString method in the Emp class and try again.

Источник

Оцените статью