The array was there in Java before the Collection framework makes its entry in JDK 1.4, hence, you will find several legacy codes, which accept an array then 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 a 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 a 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 a 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 the Iterator of HashSet will return elements in random order.
If you want to preserve the insertion order of elements or want to keep elements in the same order as they were in the array, consider using the Set implementation which preserves the insertion order i.e. LinkedHashSet.
Btw, I am expecting that you are familiar with basic Java Programing and Java API in general. If you are a complete beginner then I suggest you first go through a comprehensive course like The Complete Java MasterClass on Udemy to learn more about core Java basics as well as such gems from Java API.
Unfortunately, you cannot use this technique to convert a primitive array to a HashSet of wrapper object like you cannot convert an array of int primitive to HashSet of an Integer object because of the Arrays.asList() method doesn't allow that.=
Since you can use Arrays.asList() to convert an array to ArrayList, converting an array to HashSet is just a 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 the Iterator of HashSet will return elements in random order.
If you want to preserve the insertion order of elements or want to keep elements in the same order as they were in the array, consider using the Set implementation which preserves the insertion order i.e. LinkedHashSet.
Btw, I am expecting that you are familiar with basic Java Programing and Java API in general. If you are a complete beginner then I suggest you first go through a comprehensive course like The Complete Java MasterClass on Udemy to learn more about core Java basics as well as such gems from Java API.
How to convert an Array to HashSet in Java? Example
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 like array of Integer, an array of Double, etc.Unfortunately, you cannot use this technique to convert a primitive array to a HashSet of wrapper object like you cannot convert an array of int primitive to HashSet of an Integer object because of the Arrays.asList() method doesn't allow that.=
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.
Here is our complete Java program to convert an array to HashSet. This example uses Arrays.asList() to convert Array to List and and then to a Set. If you are running on Java 9 or higher version then you can also use List.of() instead of Arrays.asList() to create a Immutable List first.
From the output, it's clear that the input array has 5 objects but resulting in HashSet just has 4 objects because one of the String NRE was duplicate, hence not added twice on HashSet.
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); } } } Output: 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 in 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 a totally different order in array and HashSet. That's all about how to convert an array to HashSet in Java. You can use this trick to convert an array to any kind of Set in Java like HashSet, TreeSet, or even LinkedHashSet.
Other Java Collection Articles you may like
- Top 10 Courses to learn Java for Beginners (best courses)
- How to sort an ArrayList in ascending and descending order in Java? (tutorial)
- How to sort a Map by keys and values in Java? (tutorial)
- What is the difference between TreeMap and TreeSet in Java? (answer)
- Difference between ArrayList and HashSet in Java? (answer)
- Top 5 Courses to learn Java Collections and Stream (courses)
- The difference between HashSet and TreeSet in Java? (answer)
- 10 Free courses to learn Java in-depth (courses)
- Difference between Hashtable and HashMap in Java? (answer)
- Difference between HashMap and ConcurrentHashMap in Java? (answer)
- 10 courses to learn Data Structure in-depth (courses)
- The difference between HashMap and LinkedHashMap in Java? (answer)
- The difference between ArrayList and LinkedList in Java? (answer)
- 7 Best Courses to learn Data Structure and Algorithms (best courses)
- 20+ basic algorithms interview questions for programmers (questions)
- 50+ Core Java Interview Questions and Answers (questions)
- Top 5 Courses to become full-stack Java developer (courses)
- Difference between Vector and ArrayList in Java? (answer)
P. S. - On the other hand, if you want to improve your knowledge of the Java Collection framework then you can also join these best Java Collections and Stream Courses. One of the best list of advanced Java courses for any level of Java developer. You will learn a lot of new things, even if you know Java and collections already.
No comments :
Post a Comment