I have the following graph:
private final Graph<Foo, DefaultWeightedEdge> graph = buildGraph();
@Override
public Graph<Foo, DefaultWeightedEdge> buildGraph() {
return GraphTypeBuilder
.directed()
.allowingSelfLoops(false)
.weighted(true)
.allowingMultipleEdges(false)
.vertexClass(Foo.class)
.edgeClass(DefaultWeightedEdge.class)
.buildGraph();
}
How can I Map this to a Graph with Type Graph<Bar, DefaultWeightedEdge> ?
I added to Nikolais answer mapping the edge aswell, since it was not converting the source and target types of the DefaultWeightedEdge:
public <V, Vv> Graph<Vv, DefaultWeightedEdge> convert(Graph<V, DefaultWeightedEdge> source, Function<V, Vv> vertexMapper) {
Graph<Vv, DefaultWeightedEdge> result = GraphTypeBuilder.<Vv, DefaultWeightedEdge>forGraphType(source.getType()).edgeClass(DefaultWeightedEdge.class).buildGraph();
source.vertexSet().forEach(v -> result.addVertex(vertexMapper.apply(v)));
source
.edgeSet()
.forEach(
e -> {
V sourceV = source.getEdgeSource(e);
Vv mappedSourceV = vertexMapper.apply(sourceV);
V targetV = source.getEdgeTarget(e);
Vv mappedTargetV = vertexMapper.apply(targetV);
result.addVertex(mappedSourceV);
result.addVertex(mappedTargetV);
DefaultWeightedEdge ee = result.addEdge(mappedSourceV, mappedTargetV);
double edgeWeight = source.getEdgeWeight(e);
result.setEdgeWeight(ee, edgeWeight);
});
return result;
}
Could we do this more elegant in a functional / more generic way by adding an edge mapper?