Home > Java > Sets

Java | Sets

Set - is an unordered collection of unique elements.

Basics

// Create. Out: [].
Set<Integer> uniqueNumbers = new HashSet<>();

// Create with initial values. Out: [apricot, cherry, lemon].
Set<String> fruits = new HashSet<>(Arrays.asList(
  "apple",
  "apricot",
  "lemon"
));

// Get size. Out: 0, 3
uniqueNumbers.size();
fruits.size();

// Add element. Out: [11, 4]
uniqueNumbers.add(4);
uniqueNumbers.add(11);

// Check existence. Out: true, false
fruits.contains("apple");
uniqueNumbers.contains(21);

// Delete element: Out: [apricot, cherry]
fruits.remove("lemon")

Iterate

// Iterator.
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

// for-each loop
for (String element : set) {
    System.out.println(element);
}

// Using Streams.
set.stream().forEach(element -> System.out.println(element));

References