AbstractSet contains() method in Java with Example
Last Updated :
24 Dec, 2018
The contains() method of Java AbstractSet is used to check whether an element is present in a set or not. It takes the element as a parameter and returns True if the element is present in the set.
Syntax:
public boolean contains(Object element)
Parameters: The parameter element is of type set. This parameter refers to the element whose occurrence is needed to be checked in the set.
Return Value: The method returns a boolean value. It returns True if the element is present in the set otherwise it returns False.
Below programs illustrate the AbstractSet.contains() method:
Program 1:
import java.util.*;
public class GFG {
public static void main(String args[])
{
AbstractSet<String>
abs = new TreeSet<String>();
abs.add( "Geeks" );
abs.add( "for" );
abs.add( "Geeks" );
abs.add( "10" );
abs.add( "20" );
System.out.println( "AbstractSet: "
+ abs);
System.out.println( "\nDoes the set"
+ " contains 'Hello': "
+ abs.contains( "Hello" ));
System.out.println( "Does the set"
+ " contains '20': "
+ abs.contains( "20" ));
System.out.println( "Does the set"
+ " contains 'Geeks': "
+ abs.contains( "Geeks" ));
}
}
|
Output:
AbstractSet: [10, 20, Geeks, for]
Does the set contains 'Hello': false
Does the set contains '20': true
Does the set contains 'Geeks': true
Program 2:
import java.util.*;
public class GFG {
public static void main(String args[])
{
AbstractSet<Integer>
abs = new TreeSet<Integer>();
abs.add( 10 );
abs.add( 20 );
abs.add( 30 );
abs.add( 40 );
abs.add( 50 );
System.out.println( "AbstractSet:"
+ abs);
System.out.println( "\nDoes the set "
+ "contains '10': "
+ abs.contains( 10 ));
System.out.println( "\nDoes the set"
+ " contains '50': "
+ abs.contains( 50 ));
System.out.println( "Does the set"
+ " contains '100': "
+ abs.contains( 100 ));
}
}
|
Output:
AbstractSet:[10, 20, 30, 40, 50]
Does the set contains '10': true
Does the set contains '50': true
Does the set contains '100': false
Share your thoughts in the comments
Please Login to comment...