Home >Java >javaTutorial >How to Convert Arrays to Sets in Java?

How to Convert Arrays to Sets in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 16:17:261033browse

 How to Convert Arrays to Sets in Java?

Converting Arrays to Sets in Java

Converting arrays to sets in Java can be achieved using various approaches. While using loops is a straightforward method, it may be desirable to employ a more concise solution.

One efficient way to accomplish this task is by utilizing the Arrays.asList method. However, asList returns a list, which is incompatible with sets. To convert the list to a set, we can employ new HashSet. Here's an example:

<code class="java">Set<T> mySet = new HashSet<>(Arrays.asList(someArray));</code>

In Java 9 and above, you can create an unmodifiable set using Set.of:

<code class="java">Set<T> mySet = Set.of(someArray);</code>

Java 10 onwards offers type inference for generic parameters, allowing you to simplify the code:

<code class="java">var mySet = Set.of(someArray);</code>

Caution:

Set.of raises an IllegalArgumentException if there are duplicate elements in the array. For such cases, use Set.copyOf:

<code class="java">var mySet = Set.copyOf(Arrays.asList(array));</code>

This approach ensures the creation of an unmodifiable set while accommodating duplicate elements in the array.

The above is the detailed content of How to Convert Arrays to Sets in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn