Dart 语言中的集合运算

2025-05-18ASPCMS社区 - fjmyhfvclm

Dart 语言中的集合运算

Dart 的 Set 类型提供了丰富的集合运算方法,可以方便地进行集合间的操作。以下是 Dart 中主要的集合运算方法及其示例:

1. 并集 (Union)

合并两个集合中的所有元素,自动去重。

dart

Set<String> set1 = {'a', 'b', 'c'};

Set<String> set2 = {'c', 'd', 'e'};

Set<String> unionSet = set1.union(set2);

print(unionSet); // 输出: {a, b, c, d, e}

}

2. 交集 (Intersection)

返回两个集合中都存在的元素。

dart

void main() {

Set<String> set1 = {'a', 'b', 'c'};

Set<String> set2 = {'b', 'c', 'd'};

Set<String> intersectionSet = set1.intersection(set2);

print(intersectionSet); // 输出: {b, c}

}

3. 差集 (Difference)

返回在第一个集合中但不在第二个集合中的元素。

dart

void main() {

Set<String> set1 = {'a', 'b', 'c', 'd'};

Set<String> set2 = {'c', 'd', 'e'};

Set<String> differenceSet = set1.difference(set2);

print(differenceSet); // 输出: {a, b}

}

4. 补集 (Symmetric Difference)

返回只存在于其中一个集合中的元素(即并集减去交集)。

dart

void main() {

Set<String> set1 = {'a', 'b', 'c'};

Set<String> set2 = {'b', 'c', 'd'};

Set<String> symmetricDifference = set1.difference(set2).union(set2.difference(set1));

print(symmetricDifference); // 输出: {a, d}

// 或者使用更简洁的方式

Set<S

全部评论