Java - create and initialize Set<> simultaneously

5 points
Created by:

In this short article, we would like to show how to create and initialize Set<> simultaneously in Java.

Quick solution:

// import java.util.Set;

Set<String> set = Set.of("a", "b", "c");

Note: Set.of() method was intoduced in Java 9.


Practical example

import java.util.Set;

public class Program {

    public static void main(String[] args) {

        Set<Boolean> set1 = Set.of(true, false);
        Set<Integer> set2 = Set.of(1, 2, 3);
        Set<String>  set3 = Set.of("a", "b", "c");


See also

  1. Java - create and initialize Map<> simultaneously

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂