0
votes

I started learning Stream API, but can't make through this one.

I'm implementing graphs, so I have classes like so:

Graph -> Node -> Edge

Nodes in graph are stored in Hashset; Edges in Nodes too.

Here's code:

    Graph g = new Graph("Graph 1");
    g.addNode(new Node("A"));
    g.addNode(new Node("B"));
    g.connectNodes("A","B", true); //nodeA, nodeB, bidirectional

    System.out.println(g);

    g.getNodes().stream().map(Node::getConnections);

I dunno what do next with last line. At this moment it returns HashSet of edges.

I tried

    g.getNodes().stream().map(Node::getConnections).map(x->x.getNodeB().getName()).forEach(System.out::println);

to get second connected via edge node name, but IDE don't allow me to do next map.

Can you give some hints?

1
Use flatMap instead. flatMap(node -> node.getConnections().stream()) - Sergii Bishyr
Side note: You may want to rethink your API. Why would you wrap node names in Node, but then refer to them as String when connecting them? connectNodes should take in the Node type. - aglassman
Yeah, at beginning I tried to connectNodes(Node, Node), but had a real bad time getting that Nodes, because of HashSet. Now I use id as Strings in Node object. Do you have better approach? @SergheyBishyr, thanks mate, I'll give it a try. - Jump3r

1 Answers

0
votes

Using flatMap as Serghey suggested works like a charm.

g.getNodes().stream().map(Node::getConnections).flatMap(x->x.stream()).map(x->x.getNodeB().getName()).forEach(System.out::println);