How to Create a Set in Java

Published Nov 6, 2021

How do we create a set in Java?

With lists, this is an easy one-liner:

List<Integer> list = Arrays.asList(1,2,3);

What about sets?

Create a set using the constructor

The HashSet constructor allows us to pass in a list to create the set. We can statically import asList(), making this less verbose.

Set<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));

Create a set using the Stream API

We can easily create a set if we’re in Java 8.

Set<Integer> set = Stream.of(1,2,3).collect(Collectors.toSet());

Create a set using Set.of()

If we’re in Java 9, we can use Set.of() (same with List.of()).

Set<Integer> set = Set.of(1,2,3);

More Java Articles