https://www.tutorialspoint.com/java/java_set_interface.htm
Some Useful Methods:
add( )
Adds an object to the collection.
clear( )
Removes all objects from the collection.
contains( )
Returns true if a specified object is an element within the collection.
isEmpty( )
Returns true if the collection has no elements.
remove( )
Removes a specified object from the collection.
size( )
Returns the number of elements in the collection.
Example:
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e) {}
}
}
This will produce the following result − [34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
No comments:
Post a Comment