How to insert elements and print a set in Java

4 Answers

0 votes
import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        // Create a Set
        Set<String> set = new HashSet<>();

        // Add elements to the Set
        set.add("Java");
        set.add("C");
        set.add("Python");
        set.add("C++");

        // Print the Set
        System.out.println(set);
    }
}


/*
run:
  
[Java, C++, C, Python]

*/

 



answered Aug 5, 2025 by avibootz
edited Aug 5, 2025 by avibootz
0 votes
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        Iterator<Integer> iterator = numbers.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}


/*
run:
  
20
40
10
30

*/

 



answered Aug 5, 2025 by avibootz
edited Aug 5, 2025 by avibootz
0 votes
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<Double> dimensions = new HashSet<>();
        
        dimensions.add(2.36);
        dimensions.add(5.04);
        dimensions.add(0.31);

        for (Double d : dimensions) {
            System.out.println(d);
        }
    }
}


/*
run:
  
2.36
5.04
0.31

*/

 



answered Aug 5, 2025 by avibootz
0 votes
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>(Arrays.asList("Java", "C", "Python"));

        set.forEach(System.out::println);
    }
}


/*
run:
  
Java
C
Python

*/

 



answered Aug 5, 2025 by avibootz

Related questions

...