In this article we will discuss how to merge an array in a HashSet
HashSet has a member function addAll() that can add a collection into to a HashSet. But this Collection should be of Same Type as of HashSet or of its Base Class.
public boolean addAll(Collection<? extends E> c)
It will add the each element from given collection to HashSet one by one.
But an Array is not a Collection i.e.
String[] strArr = {"abc", "def", "ghi", "jkl"};
How to Merge an Array in HashSet?
Frequently Asked:
- How to create and add elements in a HashSet in Java
- How to Search for an element in HashSet in Java
- What is Hashing and Hash Table?
- How to iterate over a HashSet in Java
For this we need to first convert our array into a Collection i.e. a List. We can do this using Arrays asList() function i.e.
public static <T> List<T> asList(T... a)
It returns a fixed size List with random access provision. asList() basically acts as an adapter for using non collection based data structure in Collection based APIs.
Now we can easily merge this given List into a HashSet using addAll() function i.e.
package com.thispointer.java.collections.hashsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class Example30 { public static void main(String[] args) { // Create a new HashSet of String objects HashSet<String> setOfStrs = new HashSet<>(); // Adding elements in HashSet setOfStrs.add("hello"); setOfStrs.add("abc"); setOfStrs.add("time"); setOfStrs.add("Hi"); System.out.println("setOfStrs = " + setOfStrs); // Create an Array Of Strings String[] strArr = {"abc", "def", "ghi", "jkl"}; // Convert the String array into a Collection i.e. List List<String> arrList = Arrays.asList(strArr); // Merge the HashSet and List boolean bResult = setOfStrs.addAll(arrList); if(bResult) { System.out.println("Merging of Set & ArrayList Successfull"); } System.out.println("setOfStrs = " + setOfStrs); } }
Output:
setOfStrs = [Hi, abc, hello, time] Merging of Set & ArrayList Successfull setOfStrs = [Hi, abc, def, ghi, jkl, hello, time]