1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.grouplens.grapht.graph;
21
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.Sets;
24 import org.apache.commons.lang3.tuple.Pair;
25
26 import javax.annotation.Nonnull;
27 import java.util.Set;
28
29
30
31
32
33
34
35
36 public class DAGNodeBuilder<V,E> {
37 private V label;
38 private Set<Pair<DAGNode<V,E>,E>> edges;
39
40 public DAGNodeBuilder() {
41 this(null);
42 }
43
44 public DAGNodeBuilder(V lbl) {
45 label = lbl;
46 edges = Sets.newHashSet();
47 }
48
49
50
51
52
53
54 @Nonnull
55 public DAGNodeBuilder<V,E> setLabel(@Nonnull V lbl) {
56 Preconditions.checkNotNull(lbl, "node label");
57 label = lbl;
58 return this;
59 }
60
61
62
63
64
65 public V getLabel() {
66 return label;
67 }
68
69
70
71
72
73
74
75 @Nonnull
76 public DAGNodeBuilder<V,E> addEdge(@Nonnull DAGNode<V,E> target,
77 @Nonnull E label) {
78 Preconditions.checkNotNull(target, "edge target");
79 Preconditions.checkNotNull(label, "edge label");
80 return addEdge(Pair.of(target, label));
81 }
82
83
84
85
86
87
88 @Nonnull
89 public DAGNodeBuilder<V,E> addEdge(Pair<DAGNode<V,E>,E> edge) {
90 Preconditions.checkNotNull(edge, "edge");
91 Preconditions.checkNotNull(edge.getLeft(), "edge target");
92 Preconditions.checkNotNull(edge.getRight(), "edge label");
93 edges.add(edge);
94 return this;
95 }
96
97
98
99
100
101
102
103 @Nonnull
104 public Set<Pair<DAGNode<V,E>,E>> getEdges() {
105 return edges;
106 }
107
108 @Nonnull
109 public DAGNode<V,E> build() {
110 Preconditions.checkState(label != null, "no node label set");
111 return new DAGNode<V,E>(label, edges);
112 }
113
114 @Override
115 public String toString() {
116 return String.format("node builder with label %s and %d edges", label, edges.size());
117 }
118 }