newbie
newbie

Reputation: 111

How to Build Graph Using Java Stream API

I'm new to Java 8. I would like to use Java stream to build a graph.
For example, I have 2d array edges [[1,2,3],[1,3,3],[2,3,1]]. Each element in the array edges[i] = [ui, vi, weighti]. I use dictionary to represent my graph.

Normal Java

Map<Integer, List<int[]>> graph = new HashMap<>();
for(int[] edge: edges){
    graph.computeIfAbsent(edge[0], x -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
    graph.computeIfAbsent(edge[1], x -> new ArrayList<>()).add(new int[]{edge[0], edge[2]});
}

Is there any way using stream to do the exact same code above?

Upvotes: 0

Views: 333

Answers (1)

Tobias
Tobias

Reputation: 2575

You could replace the for loop by a Stream.forEach method like this:

Map<Integer, List<int[]>> graph = new HashMap<>();
Arrays.stream(edges).forEach(edge -> {
    graph.computeIfAbsent(edge[0], x -> new ArrayList<>()).add(new int[]{edge[1], edge[2]});
    graph.computeIfAbsent(edge[1], x -> new ArrayList<>()).add(new int[]{edge[0], edge[2]});
});

Or you could use a toMap Collector like this:

Map<Integer, List<int[]>> graph = new HashMap<>();
graph.putAll(Arrays.stream(edges).collect(Collectors.toMap(edge -> edge[0], edge -> Arrays.asList(new int[] {edge[1], edge[2]}))));
graph.putAll(Arrays.stream(edges).collect(Collectors.toMap(edge -> edge[1], edge -> Arrays.asList(new int[] {edge[0], edge[2]}))));

Upvotes: 1

Related Questions