Remove Element from LinkedHashSet Example

LinkedHashSet Examples


Java LinkedHashSet class provides following API's to remove element or elements from Set in Java:
  • remove(Object o)
  • removeAll(Collection<?> c)
  • removeIf(Predicate<? super Integer> filter)
  • clear()

Remove Element from LinkedHashSet Example

package com.javaguides.collections.linkedhashsetexamples;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class LinkedHashSetRemoveExample {
    public static void main(String[] args) {
        Set < Integer > numbers = new LinkedHashSet < > ();
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);
        numbers.add(7);
        numbers.add(8);
        numbers.add(9);
        numbers.add(10);

        System.out.println("numbers : " + numbers);

        // Remove an element from a LinkedHashSet
        boolean isRemoved = numbers.remove(10);
        System.out.println("After remove(10) => " + numbers);

        // Remove all elements belonging to a given collection from a LinkedHashSet
        List < Integer > perfectSquares = new ArrayList < > ();
        perfectSquares.add(4);
        perfectSquares.add(9);

        numbers.removeAll(perfectSquares);
        System.out.println("After removeAll(perfectSquares) => " + numbers);

        // Remove all elements matching a given predicate
        numbers.removeIf(num - > num % 2 == 0);
        System.out.println("After removeIf() => " + numbers);

        // Remove all elements from LinkedHashSet (clear it completely)
        numbers.clear();
        System.out.println("After clear() => " + numbers);
    }
}

Output

numbers : [2, 3, 4, 5, 6, 7, 8, 9, 10]
After remove(10) => [2, 3, 4, 5, 6, 7, 8, 9]
After removeAll(perfectSquares) => [2, 3, 5, 6, 7, 8]
After removeIf() => [3, 5, 7]
After clear() => []

Reference





Comments