简体   繁体   English

如何遍历以对象为键并设置对象的哈希图 <objects> 作为值并打印两者?

[英]How to iterate over a hashmap which has object as keys and set<objects> as values and print both?

I have a hashmap which take the object Node as a key and set of Nodes as values. 我有一个哈希图,该哈希图将对象Node作为键,并将Nodes集作为值。 Nodes are just an object with an integer value. 节点仅仅是具有整数值的对象。 The values are just what they are connected to in the graph. 这些值就是它们在图中连接的值。 The method addEdge just connects two nodes together, so it adds node2 to Node1's set values and vice versa. 方法addEdge只是将两个节点连接在一起,因此将node2添加到Node1的设置值中,反之亦然。

private map<Node, Set <Node>> nodeToNeighbours;
public Graph() {
   nodeToNeighbours = new TreeMap<Node, Set<Node>>();
}
public static void main (String[] args) {
   Graph test = new graph();
   Node first = new Node(5);
   Node second = new Node(6);
   Node third = new Node(7);
   test.addEdge(first, second);
   test.addEdge(first, third);
   test.toString();

}
public String toString() {
   for (Map.Entry<Node, Set <Node>> e: nodeToneighbours.entrySet()){
       System.out.println(e.getKey() + " is adjacent to " + e.getValue());
   return null;
}

What i want the output to be: 我想要的输出是:

Node 5 is adjacent to Node 6, Node 7
Node 6 is adjacent to Node 5
Node 7 is adjacent to Node 5  

The output that i'm currently getting: 我当前得到的输出:

Node 5 is adjacent to [Node 6, Node 7]
Node 6 is adjacent to [Node 5]
Node 7 is adjacent to [Node 5] 

I'm also not allowed to just go on and replace the brackets with empty strings or whatever. 我也不允许继续使用空字符串或任何其他内容替换括号。

Well you just need a different way of converting a Set<Node> to a String . 好吧,您只需要将Set<Node>转换为String的另一种方法。 Currently you're using the default toString() implementation, but it's easy to write your own, eg 当前,您正在使用默认的toString()实现,但是编写自己的实现很容易,例如

private static String commaSeparate(Iterable<?> items) {
    StringBuilder builder = new StringBuilder();
    for (Object item : items) {
        if (builder.length() != 0) {
            builder.append(", ");
        }
        builder.append(item);
    }
    return builder.toString();
}

Or use the Joiner class from Guava , or StringJoiner from Java 8, both of which are designed for this sort of thing. 或使用GuavaJoiner类或Java 8的StringJoiner ,两者都是针对此类事情而设计的。

Either way, you then use the formatted string in your output: 无论哪种方式,您都可以在输出中使用格式化的字符串:

System.out.println(e.getKey() + " is adjacent to " + commaSeparate(e.getValue()));

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

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