简体   繁体   English

在 Java 中打印 HashMap

[英]Printing HashMap In Java

I have a HashMap :我有一个HashMap

private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, 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?我的意思是如果它有 1 个键和值,大小是 0 还是 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. keySet()仅从您的哈希映射中返回一组键,您应该迭代此键集并使用这些键从哈希映射中获取值。

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.在您的示例中,哈希映射键的类型是TypeKey ,但您在通用for-loop指定了TypeValue ,因此无法编译它。 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: 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?我的意思是如果它有 1 个键和值,它的大小是 0 还是 1?

The collection returned from keySet() is aSet .keySet()返回的集合是一个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.如果您的哈希映射只有一个键,则返回的keySet()将包含一个条目,其大小为 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:方法 1 和方法 2 都输出:

[{b=2, a=1}]

Assuming you have a Map<KeyType, ValueType> , you can print it like this:假设你有一个Map<KeyType, ValueType> ,你可以这样打印:

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你有几个选择

Worth mentioning Java 8 approach, using BiConsumer and lambda functions:值得一提的是 Java 8 方法,使用BiConsumer和 lambda 函数:

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.假设您已经根据需要覆盖了两种类型的toString方法。

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!您提供的代码甚至无法编译,这在以后的问题中可能值得一提——“似乎不起作用”有点含糊!

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这是有效的,因为toString()方法已经在AbstractMap class中被覆盖, AbstractMap classHashMap Class扩展。文档中的更多信息

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 ("{}").字符串表示由一个键值映射列表组成,按映射的 entrySet 视图的迭代器返回的顺序排列,括在大括号(“{}”)中。 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).键和值通过 String.valueOf(Object) 转换为字符串。

对我来说,这个简单的一行运行良好:

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

使用 java 8 特性

Java 8 new feature forEach style Java 8 forEach风格的新特性

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

    }
}

用于快速打印 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());
}

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.如果映射将集合作为值保存,则其他答案需要额外的努力才能将它们转换为字符串,例如Arrays.deepToString(value.toArray()) (如果它是列表值的映射)等。

I faced these issues quite often and came across the generic function to print all objects using ObjectMappers .我经常遇到这些问题,并遇到了使用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.您可以使用Entry类轻松读取HashMap

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

Using java 8 feature:使用 java 8 功能:

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

Using Map.Entry you can print like this:使用 Map.Entry 你可以这样打印:

 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.:使用entryset()方法将HashMap转换为MapSet以获取Map的条目集。:
    Set dataset = map.entrySet();
  • Get the iterator of this set:获取这个集合的迭代器:
    Iterator it = dataset.iterator();
  • Get Map.Entry from the iterator:从迭代器获取Map.Entry
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to retrive keys and values.使用Map.Entry getKey()getValue()方法来检索键和值。
Set dataset = (Set) map.entrySet();
Iterator it = dataset.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM