Sunday, March 6, 2016

How to convert an Array to HashSet in Java - Example Tutorial

The array was there in Java before the Collection framework makes its entry in JDK 1.4, hence, you will find several legacy code, which accepts array than the Collection or Set. Due to this, we often need to convert an array to different types of collection e.g. List or Set. Earlier, I have told you the trick to convert an array to list and today I'll teach you how to convert an array to HashSet by using the same technique. The concept you need to know is that Collection provides a copy constructor i.e. you can pass a collection to create another collection. We'll leverage the same fact and to create an HashSet, we'll pass an ArrayList. Since you can use Arrays.asList() to convert an array to ArrayList, converting an array to HashSet is just two step job, first convert an array to a list and then convert a list to set.

When you convert an array to HashSet in Java, you need to keep a couple of things in your mind. Why? because the characteristic of array and HashSet is totally different, for example, when you iterate over HashSet, you will not get the elements in any particular order because Iterator of HashSet will return elements in random order. If you want to preserve the insertion order of element or want to keep elements in same order as they were in the array, consider using the Set implementation which  preserves the insertion order i.e. LinkedHashSet.

The array is also an ordered data structure and allows duplicates but HashSet doesn't guarantee any order and doesn't allow duplicate elements as well. What this means, if you have a duplicate element in your array, that will be lost when you convert the array to HashSet. Actually, this is also a cool trick to remove duplicates from the array in Java, one of the frequently asked coding questions from Java programming job interviews.

If you are preparing for Java interviews, then you need to remember these kinds of details to answer Java collection based interview questions. Though for a more complete and thorough preparation, I recommend reading the book Java Programming Interview Exposed at least one time before going to interviews. It covers all major topics for Java J2EE interviews including frameworks like Spring and Hibernate.

How to convert Array to HashSet in Java

On the other hand, if you want to improve knowledge of Java Collection framework then you can either refer Core Java Volume 1 9th Edition by Cay S. Horstman. One of the best core Java book for any level of Java developer. You will learn a lot of new things, even if you know Java and collections already.

Java Program to convert Array to HashSet in Java

Now, let's see an example of the process we have discussed to convert an array to HashSet. In our example, we will convert an array to String to HashSet of String, but you can use this technique to convert any reference type of array to HashSet e.g. array of Integer, array of Double etc.

Unfortunately, you cannot use this technique to convert a primitive array to HashSet of wrapper object e.g. you cannot convert an array of int primitive to HashSet of Integer object because Arrays.asList() method doesn't allow that.

import java.util.Arrays;
import java.util.HashSet;

* Java example to demonstrate how to convert an array to HashSet.
* This example uses Arrays.asList() method to perform the
* conversion. 
public class ArrayToHashSet{

public static void main(String args[]) {

// let's create an array of String
String[] nriAccounts = {"NRE", "NRO", "FCNR", "RFC", "NRE"};

// let's convert this array to HashSet in Java
// if array contains any duplicate than that would be lost
HashSet<String> setOfAccounts = new HashSet<>(Arrays.asList(nriAccounts));

System.out.println("Array contains: " + Arrays.toString(nriAccounts));
System.out.println("HashSet contains: " + setOfAccounts);

// if array contains duplicate than HashSet will have fewer
// elements than array
System.out.println("length of array: " + nriAccounts.length);
System.out.println("size of HashSet: " + setOfAccounts.size());

// Elements order will not be preserved when you convert an 
// array to HashSet in Java, as Set is an unordered collection.

System.out.println("Iterating over array in Java");
for(String account: nriAccounts){
System.out.println("array: " + account);

System.out.println("Iterating over HashSet in Java");
for(String account: setOfAccounts){
System.out.println("hashset: " + account);



Array contains: [NRE, NRO, FCNR, RFC, NRE]
HashSet contains: [FCNR, NRO, RFC, NRE]
length of array: 5
size of HashSet: 4
Iterating over array in Java
array: NRE
array: NRO
array: FCNR
array: RFC
array: NRE
Iterating over HashSet in Java
hashset: FCNR
hashset: NRO
hashset: RFC
hashset: NRE

From the output, it's clear that the input array has 5 objects but resulting HashSet just has 4 objects because one of the String NRE was duplicate, hence not added twice on HashSet. It's also clear that the order of elements is not preserved and when you iterate, you will encounter order in totally different order in array and HashSet. That's all about how to convert an array to HashSet in Java.

Further Learning
Java Fundamentals: The Java Language by Jim Wilson
Java Fundamentals: Collections
Java Programming Interview Exposed

No comments :

Post a Comment