开发者

Printing HashMap In Java

I have a HashMap:

private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey,开发者_JAVA百科 TypeValue>();

Now I would like to run through all the values and print them.

I wrote this:

for (TypeValue name : this.example.keySet()) {
    System.out.println(name);
}

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?


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()) {
    String key = name.toString();
    String value = example.get(name).toString();
    System.out.println(key + " " + value);
}

Update for Java8:

example.entrySet().forEach(entry -> {
    System.out.println(entry.getKey() + " " + entry.getValue());
});

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<String, Integer> 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:

[{b=2, a=1}]


Assuming you have a Map<KeyType, ValueType>, you can print it like this:

for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
    System.out.println(entry.getKey()+" : "+entry.getValue());
}


To print both key and value, use the following:

for (Object objectName : example.keySet()) {
   System.out.println(objectName);
   System.out.println(example.get(objectName));
 }


You have several options

  • 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())


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

HashMap<K,V> 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 ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).


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

Using java 8 features


You want the value set, not the key set:

for (TypeValue name: this.example.values()) {
        System.out.println(name);
}

The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!


Worth mentioning Java 8 approach, using BiConsumer and lambda functions:

BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) -> 
           System.out.println(o1 + ", " + o2);

example.forEach(consumer);

Assuming that you've overridden toString method of the two types if needed.


Java 8 new feature forEach style

import java.util.HashMap;

public class PrintMap {
    public static void main(String[] args) {
        HashMap<String, Integer> example = new HashMap<>();
        example.put("a", 1);
        example.put("b", 2);
        example.put("c", 3);
        example.put("d", 5);

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

//      Output:
//      a : 1
//      b : 2
//      c : 3
//      d : 5

    }
}


Useful to quickly print entries in a HashMap

System.out.println(Arrays.toString(map.entrySet().toArray()));


I did it using String map (if you're working with String Map).

for (Object obj : dados.entrySet()) {
    Map.Entry<String, String> entry = (Map.Entry) obj;
    System.out.print("Key: " + entry.getKey());
    System.out.println(", Value: " + entry.getValue());
}


Using java 8 feature:

    map.forEach((key, value) -> System.out.println(key + " : " + value));

Using Map.Entry you can print like this:

 for(Map.Entry entry:map.entrySet())
{
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

Traditional way to get all keys and values from the map, you have to follow this sequence:

  • Convert HashMap to MapSet to get set of entries in Map with entryset() method.:
    Set dataset = map.entrySet();
  • Get the iterator of this set:
    Iterator it = dataset.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to retrive keys and values.
Set dataset = (Set) map.entrySet();
Iterator it = dataset.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}


Print a Map using java 8

Map<Long, String> productIdAndTypeMapping = new LinkedHashMap<>();
productIdAndTypeMapping.forEach((k, v) -> log.info("Product Type Key: " + k + ": Value: " + v));


If the map holds a collection as value, the other answers require additional effort to convert them as strings, such as Arrays.deepToString(value.toArray()) (if its a map of list values), etc.

I faced these issues quite often and came across the generic function to print all objects using ObjectMappers. This is quite handy at all the places, especially during experimenting things, and I would recommend you to choose this way.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public static String convertObjectAsString(Object object) {
    String s = "";
    ObjectMapper om = new ObjectMapper();
    try {
        om.enable(SerializationFeature.INDENT_OUTPUT);
        s = om.writeValueAsString(object);
    } catch (Exception e) {
        log.error("error converting object to string - " + e);
    }
    return s;
}


You can use Entry class to read HashMap easily.

for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){
    System.out.println(temp.getValue()); // Or something as per temp defination. can be used
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜