Thursday, 24 May 2012

Convert Arrays to Set in Java .

Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often.
However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an Java Array to ArrayList, I have seen people writing loops instead of simple Arrays.asList().
Here is a simple writeup on Converting Java Arrays to ArrayList that I wrote a while ago.
One of such simple requirement is to convert Java Arrays to Set. While working with Hibernate, I once had to convert a Java Arrays that we used to populate from UI and convert it into Set. While this is a simple task, most often one may end up writing for loop.
Here is a dead simple trick. Use below code to Convert Arrays to Set in Java.

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
Tanaa!!! Simple isn’t it. Its like “I already knew that” stuff.
Notice how we have used Generics also in above code snippet. Thus if you have an ArrayList than you can convert it to Set with one simple line of code.
Checkout below example:

Example: Java Array to Set

String [] countires = {"India", "Switzerland", "Italy"};
Set<String> set = new HashSet<String>(Arrays.asList(countires));

[Italy, Switzerland, India]

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...