Skip to main content

HashSet

java.util.HashSet CLASS

caution
  • HashSet is a collection that contains no duplicate elements.
  • HashSet does not maintain any particular order
  • HashSet cannot be called by Index No. as it does not maintain any particular order
  • Unlike Java arrays or ArrayLists, Sets are not indexed. So, if we want to access the values in our Set, HashSet, TreeSet or LinkedHashSet, we need to use the iterator() method and iterate through each value. iterator() method is part of the java.util.Iterator package, so we’ll have to import the java.util.Iterator package before we can use the iterator() method.
  • Collections.sort() is not applicable to 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 HashSet along with all the methods of Set.

Declare with Set

  • Set is an Inteface which HashSet class can implement.
Set<Integer> variableName = new HashSet<>();
  • It will not contain HashSet methods.

caution
  • HashSet<DataType> variable_name = new HashSet<>(capacity, loadFactor);

The main components of a HashSet are as follows:

  • HashSet tells 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_name is the name of our hash set.
  • new HashSet<> initializes a HashSet and assigns it to variable_name.
  • capacity states how many values the hash set can store. By default, this is set to 8. (optional)
  • loadFactor specifies 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

Printing as it is

System.out.println(hashSetName);
// [65, 4, 565, 6, 54]

Using for-Each loop

for (int el : hashSetName) {
System.out.print(el + " ");
}

Access Elements from HashSet

caution
  • Unlike Java arrays or ArrayLists;; Sets are not indexed. So, if we want to access the values in our Set, HashSet, TreeSet or LinkedHashSet, we need to use the iterator() method and iterate through each value. iterator() method is part of the java.util.Iterator package, so we’ll have to import the java.util.Iterator package before we can use the iterator() 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() returns true if the cololection outside the bracket contains all the elements of the collection inside the bracket or false
  • 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() becuase variableName.clone() is an Object Type and Object Types must convert to HashSet<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]

forEach()


spliterator()


stream()