I have a hashmap which take the object Node as a key and set of Nodes as values. 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.
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
. Currently you're using the default toString()
implementation, but it's easy to write your own, e.g.
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.
Either way, you then use the formatted string in your output:
System.out.println(e.getKey() + " is adjacent to " + commaSeparate(e.getValue()));
See more on this question at Stackoverflow