Use the similar method as Number of Islands II. Use a findRoot function. See more details in https://leetcode.com/discuss/69572/easiest-java-solution-with-explanations

```
public int countComponents(int n, int[][] edges) {
int res = n;
int[] root = new int[n];
for (int i = 0; i < n; i++) {
root[i] = i;
}
for (int[] pair : edges) {
int rootX = findRoot(root, pair[0]);
int rootY = findRoot(root, pair[1]);
if (rootX != rootY) {
root[rootY] = rootX;
res--;
}
}
return res;
}
public int findRoot(int[] root, int i) {
while (root[i] != i) i = root[i];
return i;
}
```