How to Initialize HashSet with Multiple Elements in Java
Table of Contents
Java is popular because of all the built-in data structures available for you right out of the box.
One of the most useful data structures is the HashSet, which is a collection of unique elements. It is a great way to store a collection of elements without worrying about duplicates.
In this article, we will look at multiple ways to initialize a HashSet with multiple elements in Java.
Stream.of()
The most modern way to initialize a HashSet is to use the Stream.of()
method.
This method takes a variable number of arguments and returns a stream of those arguments.
You can then use the stream to initialize a HashSet.
Here's how that looks:
JAVASet<String> set = Stream.of("a", "b", "c").collect(Collectors.toSet());
By using the toSet()
method, we can convert the stream to a HashSet.
Arrays.asList()
Another way to accomplish this task is by using the Arrays.asList()
method.
This method takes a variable number of arguments and returns a list of those arguments, perfect for our use case.
Using that list, we can pass it natively to the HashSet constructor to create a new HashSet.
Let's take a look at how that works:
JAVASet<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));
Both of these approaches are valid, it just depends if you want to use the more modern stream approach or the more traditional approach.
Conclusion
In this post, we looked at how to initialize a HashSet with multiple elements in Java.
You can either use the Stream.of()
method or the Arrays.asList()
method to get the job done.
Thanks for reading!
- Getting Started with Svelte
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API