Set/HashSet/KeySet
Abstractions
C++
Standard Library:
std::set
: Similar toabsl::btree_set
, provided by the standard but significantly less performant.std::unordered_set
: Similar toabsl::flat_hash_set
, provided by the standard but significantly less performant.
Abseil:
absl::flat_hash_set
: an unordered collection of unique values.absl::node_hash_set
: Similar to absl::flat_hash_set, but uses separate allocations for the entries, thus providing pointer stability;absl::btree_set
: an ordered collection of unique values.
JavaScript
Set
Rust
std::collections::HashSet
, std::collections::BTreeSet
Create
Java
Init EnumSet
EnumSet.of(Style.BOLD, Style.ITALIC);
JavaScript
const foo = new Set();
Python
Create Set
:
>>> a = [1, 2, 2, 3, 3, 3]
>>> set(a)
{1, 2, 3}
Create FrozenSet:
>>> a = [1, 2, 2, 3, 3, 3]
>>> frozenset(a)
frozenset({1, 2, 3})
Create: From Existing
Add / Remove Element
JavaScript
fooSet.add(1);
fooSet.delete(1);
Python
New elements can be added to set
:
>>> s1 = set([1,2,3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}
but not to frozenset
>>> s2 = frozenset([1,2,3])
>>> s2.add(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
Contains
C++
absl::flat_hash_set<std::string> n = {"a", "b", "c"};
n.contains("a");
JavaScript
fooSet.has(1);
Python
Use in
>>> 1 in set([1,2,3])
True
>>> 4 in set([1,2,3])
False
>>> 4 not in set([1,2,3])
True
Join As String
Python
>>> "".join(s)
'ba'
Union
Intersection
Java
Use the retainAll() method of Set:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
Find duplicates
Python
import collections
print([col for col, count in collections.Counter(header_trim).items() if count > 1])
Remove Duplicates
Java
Collection<Type> noDups = new HashSet<Type>(c);
Collection<Type> noDups = new LinkedHashSet<Type>(c);
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
Convert From Set
JavaScript
const arr = [1, 2, 3];
const set = new Set(arr);