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));
Code language: Java (java)

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 [] countries = {"India", "Switzerland", "Italy"}; Set<String> set = new HashSet<String>(Arrays.asList(countries)); System.out.println(set);
Code language: Java (java)

Output:

[Italy, Switzerland, India]
Code language: Java (java)

Hope this is useful.

View Comments

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago