Wednesday 27 May 2015

How to Remove Set From HashSet

package com.javapro.hashset;

import java.util.HashSet;
import java.util.Set;

public class RemoveAll {

    public static void main(String[] args) {

        Set<String> hs = new HashSet<String>();
        hs.add("java");
        hs.add("php");
        hs.add("html");
        hs.add("javascript");
        hs.add("mysql");

        // print hashset
        System.out.println("Before Remove Element hs = " + hs);

        HashSet<String> hs2 = new HashSet<String>();
        hs2.add("java");
        hs2.add("html");
        hs2.add("two");

        System.out.println("hs2 is = " + hs2);

        /*
         * Removes from hs set all of its elements that are contained in the hs2
         * collection
         */

        hs.removeAll(hs2);

        System.out.println("After Remove All hs = " + hs);

    }

}

Output:

Before Remove Element hs = [javascript, php, html, java, mysql]


hs2 is = [two, html, java]

After Remove All hs = [javascript, php, mysql]



No comments:

Post a Comment