Avatar ·

How to initialize a HashSet with a set of values at creation

Hi everyone! I just started learning Java and ran into a problem. I need to create a HashSet that already contains several elements at creation. In Python, I can simply write `my_set = {1, 2, 3}` and it's done. But in Java, I can't find a simple way to do this. Here's what I tried: ```java Set mySet = new HashSet("a", "b", "c"); // Compilation error ``` This doesn't work. Then I tried: ```java Set mySet = new HashSet(); mySet.add("a"); mySet.add("b"); mySet.add("c"); ``` This works, but it results in many lines of code. I need to initialize a set with 10-20 values, and this approach looks terrible. I know that Java 9 introduced `List.of()`, `Set.of()`, and `Map.of()`, but I'm using Java 8 at work. Please advise