Polyglot CheatSheet - Set/HashSet/KeySet
Updated: 2020-06-29
Create
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})
Hack
$k = keyset['foo', 'bar'];
Create: From Existing
Hack
$k = keyset($container);
Add Element
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'
Hack
$k[] = 'baz';
Remove Element
Hack
unset($k['baz']);
Contains
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
Hack
C\contains_key($k, 'foo')
Count
Hack
C\count($k)
Type Signature
Hack
keyset<TKey>
Type Of
Hack
is_keyset($k)
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 To Other Collections
Hack
keyset to Vector
new Vector($k)
keyset to Map
new Map($k)
keyset to Set
new Set($k)
keyset to array
Arrays::fromKeyset($v)