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 with one simple line of code.
ArrayList
than you can convert it to SetCheckout below example:
Example: Java Array to Set
1 2 3 4 | String [] countires = { "India" , "Switzerland" , "Italy" }; Set<String> set = new HashSet<String>(Arrays.asList(countires)); System.out.println(set); |
Output:
[Italy, Switzerland, India] |
No comments:
Post a Comment