set
# You can't create a set like this in Python
my_set = {} # ---- This is a Dictionary/Hashmap
# To create a empty set you have to use the built in method:
my_set = set() # Correct!
set_example = {1,3,2,5,3,6}
print(set_example)
# OUTPUT
# {1,3,2,5,6} ---- Sets do not contain duplicates and are unordered
3.2
5
Set<String> names = new HashSet<>();
names.add("John");
names.add("Jack");
names.add("John");
System.out.println(names); // [John, Jack]
names.remove("John");
boolean contains = names.contains("Jack"); // true
for (String name: names) {
System.out.println(name);
}
Thank you!
5
0
3
1
@echo off
set a[0]=1
set a[1]=2
set a[2]=3
Rem Setting the new value for the second element of the array
Set a[1]=5
echo The new value of the second element of the array is %a[1]%
Thank you!
1
0
4
10
When to use List, Set and Map?
If we need to access elements frequently by using index, then List is a way
to go ArrayList provides faster access if we know index.
If we want to store elements and want them to maintain an order,
then go for List again. List is an ordered collection and maintain order.
If we want to create collection of unique elements and don't want
any duplicate than choose any Set implementation. (HashSet... )
If we want store data in form Key and Value than Map is the way to go.
We can choose from HashMap, Hashtable...
Thank you!
10
0
0
0
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # show that duplicates have been removed
# OUTPUT {'orange', 'banana', 'pear', 'apple'}
print('orange' in basket) # fast membership testing
# OUTPUT True
print('crabgrass' in basket)
# OUTPUT False
# Demonstrate set operations on unique letters from two words
print(a = set('abracadabra'))
print(b = set('alacazam'))
print(a) # unique letters in a
# OUTPUT {'a', 'r', 'b', 'c', 'd'}
print(a - b) # letters in a but not in b
# OUTPUT {'r', 'd', 'b'}
print(a | b) # letters in a or b or both
# OUTPUT {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
print(a & b) # letters in both a and b
# OUTPUT {'a', 'c'}
print(a ^ b) # letters in a or b but not both
# OUTPUT {'r', 'd', 'b', 'm', 'z', 'l'}
Thank you!
0
0
0
2
SET: Can only store unique values,
And does not maintain order
- HashSet can have null, order is not guaranteed
- LinkedHashSet can have null and keeps the order
- TreeSet sorts the order and don't accept null
Thank you!
2
0
Are there any code examples left?
New code examples in category Other