HashSet
java.util.HashSet CLASS
caution
HashSetis a collection that contains no duplicate elements.HashSetdoes not maintain any particular orderHashSetcannot be called byIndex No.as it does not maintain any particular order- Unlike Java
arraysorArrayLists,Setsare not indexed. So, if we want to access the values in ourSet,HashSet,TreeSetorLinkedHashSet, we need to use the iterator() method and iterate through each value.iterator()method is part of thejava.util.Iteratorpackage, so we’ll have to import thejava.util.Iteratorpackage before we can use theiterator()method. Collections.sort()is not applicable toHashSet.
tip
REFERENCE:~
- Official Documentation:-
Java 14java.util.HashSethttps://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/HashSet.html - https://careerkarma.com/blog/java-hashset/
- https://www.baeldung.com/java-initialize-hashset
Declaration
info
Declare with HashSet ~ BEST METHOD
HashSet<Integer> hs = new HashSet<>();
// Its capacity changes as new values are added.
//Default capacity is 8
- It is the BEST METHOD as it will contain all the methods of the
HashSetalong with all the methods ofSet.
Declare with Set
Setis anIntefacewhichHashSet classcan implement.
Set<Integer> variableName = new HashSet<>();
- It will not contain
HashSetmethods.
caution
HashSet<DataType> variable_name = new HashSet<>(capacity, loadFactor);
The main components of a HashSet are as follows:
HashSettells our program we want to declare a HashSet.<DataType>is the type of data that is held by the values stored in the hash set.variable_nameis the name of our hash set.new HashSet<>initializes a HashSet and assigns it to variable_name.capacitystates how many values the hash set can store. By default, this is set to 8.(optional)loadFactorspecifies that when a hash set is filled by a certain amount, the elements within the table are moved to a new table double the size of the original table. By default, this is set to 0.75 (or 75% capacity).(optional)
Initialisation from user input
using add() and while loop
HashSet<String> hs = new HashSet<>();
while (sc.hasNext()) {
hs.add(sc.next());
}
using addAll(anotherCollectionName)
info
Taking the elements from other Collections such as HashSet, ArrayList, LinkedList, etc.
hashSetName.addAll(ArrayListName)
HashSet<Integer> hs = new HashSet<>();
ArrayList<Integer> al = new ArrayList<>();
al.add(4);
al.add(6);
al.add(65);
al.add(54);
al.add(565);
al.add(65);
// ArrayList "al" becommes [4, 6, 65, 54, 565, 65]
hs.addAll(al); //"hs" becomes [65, 4, 565, 6, 54]
// HashSet "hs" can only store UNIQUE(no Duplicates) elements, So "hs" removed element "65" as it was repeated TWICE
// HashSet never maintains the order of elements, It jumbles up the order.
- This can also be done by👇:
ArrayList<Integer> al = new ArrayList<>();
al.add(4);
al.add(6);
al.add(65);
al.add(54);
al.add(565);
al.add(65);
HashSet<Integer> hs new HashSet<>(al);
//"hs" gets initialised with [65, 4, 565, 6, 54]
Less used Approaches:
- Need to avoid👇:
Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));
Set<String> set = new HashSet<>(ArrayList.addAll("a", "b", "c"));
Set<String> set = new HashSet<>(Collections.addAll("a", "b", "c"));
Assigning Single Elements
Set<Integer> hs = new HashSet<>();
Collections.addAll(hs, 1,2,3,4,5,6);
caution
HashSet can only store UNIQUE elements
HashSet never maintains the order of elements, it jumbles up the order.
Printing HashSet
info
Access Elements from HashSet
caution
- Unlike Java
arraysorArrayLists;;Setsare not indexed. So, if we want to access the values in ourSet,HashSet,TreeSetorLinkedHashSet, we need to use theiterator()method and iterate through each value.iterator()method is part of thejava.util.Iteratorpackage, so we’ll have to import thejava.util.Iteratorpackage before we can use theiterator()method.
Using Iterator
HashSet<String> hs = new HashSet<>();
while (sc.hasNext()) {
hs.add(sc.next());
}
Iterator<Integer> it = hs.iterator(); // Here ".iterator()" method is a method of `HashSet" class :~ "java.util.HashSet.iterator()"
while (it.hasNext()) { // ".hasNext()" method is a method of `Iterator" Interface
System.out.print(it.next() + " "); // ".next()" method is a method of `Iterator" Interface
}
Using for-Each loop
HashSet<Integer> hs = new hashSet<>();
while (sc.hasNext()) {
hs.add(sc.next()); // Assigning String inputs to the HashSet "hs"
}
while (String el : hs) {
System.out.print(el + " ");
}
HashSet Methods
size()
HashSet<Integer> hs = new hashSet<>();
hs.add(45);
hs.add(85);
hs.add(56);
hs.add(420);
System.out.println(hs.size()); //prints the size is 4
add()
HashSet<Integer> hs = new HashSet<>();
while (sc.hasNext()) {
hs.add(sc.nextInt());
}
addAll()
HashSet UNION
HashSet<String> hs = new HashSet<>();
ArrayList<String> al = new ArrayList<>();
// ArrayList "al" has ["My", "name", "is", "Sarthak"]
hs.addAll(al); // HashSet "hs" becomes ["My", "name", "is", "Sarthak"]
remove()
HashSet<String> hs = new HashSet<>();
// HashSet "hs" has ["My", "name", "is", "Sarthak"]
hs.remove("name"); //"hs" becomes ["My", "is", "Sarthak"]
removeAll()
toArray()
toString()
clear()
contains()
containsAll()
HashSet INTERSECTION
containsAll()returnstrueif the cololection outside the bracket contains all the elements of the collection inside the bracket orfalse- It checks whether the collection inside the bracket is a subset of collection outside the bracket
- It checks whether the collection outside the bracket is a superset of collection inside the bracket
HashSet<String> hs1 = new HashSet<>(); // ["guava", "mango", "orange"]
ArrayList<String> al = new ArrayList<>(); // ["apple", "orange", "guava", "grapes"]
System.out.println(hs.containsAll(al)); // prints "false"
// 👆returns "true" or "false" if "hs" contain ALL elements of "al" or not
retainAll()
- Retains the common elements between two
Collections
HashSet<String> hs1 = new HashSet<>(); // ["guava", "mango", "orange"]
ArrayList<String> al = new ArrayList<>(); // ["apple", "orange", "guava", "grapes"]
hs.retainAll(al); // ["guava", "orange"]
// 👆gives the common elements between both "Collections"
isEmpty()
iterator()
equals()
hashCode()
clone()
caution
- MUST
Type Cast->variableName.clone()as(HashSet<Integer>) hs.clone()becuasevariableName.clone()is anObject TypeandObject Typesmust convert toHashSet<Integer>for code to execute.
HashSet<Integer> hs = new HashSet<>();
hs.add(89);
hs.add(45);
hs.add(65);
HashSet<Integer> hs2 = new HashSet<>();
hs2 = (HashSet) hs.clone();
System.out.println(hs2); // prints [89, 45, 65]
ALSO 👇
HashSet<Integer> hs = new HashSet<>();
hs.add(89);
hs.add(45);
hs.add(65);
HashSet<Integer> hs2 = new HashSet<>();
hs2 = (HashSet<Integer>) hs.clone();
System.out.println(hs2); // prints [89, 45, 65]