How To Get An Element From Set In Java
The ready interface is present in java.util package and extends the Drove interface is an unordered collection of objects in which duplicate values cannot be stored. Information technology is an interface that implements the mathematical ready. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. At that place are two interfaces that extend the fix implementation namely SortedSet and NavigableSet.
In the higher up image, the navigable gear up extends the sorted gear up interface. Since a set doesn't retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable ready is a TreeSet which is an implementation of a cocky-balancing tree. Therefore, this interface provides u.s. with a way to navigate through this tree.
Declaration: The Set interface is declared as:
public interface Set up extends Collection
Creating Set Objects
Since Gear up is an interface, objects cannot be created of the typeset. We always demand a class that extends this list in gild to create an object. And too, after the introduction of Generics in Java 1.five, it is possible to restrict the type of object that can be stored in the Set. This type-safe gear up tin be defined as:
// Obj is the type of the object to be stored in Set Set<Obj> set = new HashSet<Obj> ();
Let us talk over methods present in the Prepare interface provided below in a tabular format below every bit follows:
Method | Description |
---|---|
add together(element) | This method is used to add a specific element to the ready. The function adds the element simply if the specified element is not already present in the gear up else the part returns Simulated if the element is already present in the Set. |
addAll(collection) | This method is used to append all of the elements from the mentioned drove to the existing set. The elements are added randomly without following any specific lodge. |
clear() | This method is used to remove all the elements from the gear up but non delete the set. The reference for the set still exists. |
contains(element) | This method is used to bank check whether a specific element is nowadays in the Set or not. |
containsAll(collection) | This method is used to check whether the set contains all the elements present in the given collection or non. This method returns true if the gear up contains all the elements and returns false if any of the elements are missing. |
hashCode() | This method is used to go the hashCode value for this case of the Set. It returns an integer value which is the hashCode value for this instance of the Prepare. |
isEmpty() | This method is used to cheque whether the gear up is empty or non. |
iterator() | This method is used to return the iterator of the prepare. The elements from the set are returned in a random order. |
remove(chemical element) | This method is used to remove the given element from the gear up. This method returns Truthful if the specified element is nowadays in the Set otherwise it returns False. |
removeAll(drove) | This method is used to remove all the elements from the drove which are present in the set up. This method returns true if this ready changed equally a result of the call. |
retainAll(drove) | This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the telephone call. |
size() | This method is used to get the size of the set. This returns an integer value which signifies the number of elements. |
toArray() | This method is used to form an assortment of the same elements equally that of the Set. |
Illustration: Sample Plan to Illustrate Set interface
Java
import
java.util.*;
public
grade
GFG {
public
static
void
main(Cord[] args)
{
Set<String> hash_Set =
new
HashSet<Cord>();
hash_Set.add(
"Geeks"
);
hash_Set.add together(
"For"
);
hash_Set.add(
"Geeks"
);
hash_Set.add(
"Example"
);
hash_Set.add(
"Set"
);
System.out.println(hash_Set);
}
}
Output
[Set up, Example, Geeks, For]
Operations on the Ready Interface
The gear up interface allows the users to perform the basic mathematical operation on the set. Let's have two arrays to understand these bones operations. Let set1 = [one, 3, 2, 4, 8, 9, 0] and set2 = [i, 3, 7, 5, 4, 0, vii, five]. Then the possible operations on the sets are:
1. Intersection: This operation returns all the common elements from the given ii sets. For the higher up ii sets, the intersection would be:
Intersection = [0, 1, three, 4]
2. Union: This operation adds all the elements in one set with the other. For the above two sets, the union would be:
Union = [0, one, 2, iii, 4, v, 7, eight, 9]
3. Difference: This functioning removes all the values present in 1 set from the other set. For the above two sets, the divergence would be:
Difference = [2, viii, 9]
At present let u.s.a. implement the following operations equally divers above as follows:
Instance:
Java
import
java.util.*;
public
class
SetExample {
public
static
void
main(String args[])
{
Ready<Integer> a =
new
HashSet<Integer>();
a.addAll(Arrays.asList(
new
Integer[] {
1
,
3
,
two
,
4
,
8
,
9
,
0
}));
Gear up<Integer> b =
new
HashSet<Integer>();
b.addAll(Arrays.asList(
new
Integer[] {
ane
,
3
,
seven
,
v
,
4
,
0
,
vii
,
5
}));
Set<Integer> spousal relationship =
new
HashSet<Integer>(a);
union.addAll(b);
System.out.print(
"Union of the two Set"
);
System.out.println(union);
Set<Integer> intersection =
new
HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print(
"Intersection of the ii Fix"
);
System.out.println(intersection);
Set<Integer> difference =
new
HashSet<Integer>(a);
difference.removeAll(b);
System.out.print(
"Deviation of the 2 Set"
);
System.out.println(difference);
}
}
Output
Union of the two Set[0, 1, 2, 3, 4, 5, 7, viii, nine] Intersection of the two Ready[0, 1, iii, 4] Divergence of the two Set[2, viii, ix]
Performing Various Operations on SortedSet
After the introduction of Generics in Java 1.v, information technology is possible to restrict the type of object that can be stored in the Set. Since Set is an interface, it can be used only with a course that implements this interface. HashSet is one of the widely used classes which implements the Set interface. Now, allow'due south see how to perform a few frequently used operations on the HashSet. We are going to perform the post-obit operations as follows:
- Adding elements
- Accessing elements
- Removing elements
- Iterating elements
- Iterating through Set up
Now permit us talk over these operations individually as follows:
Operations 1: Calculation Elements
In social club to add an element to the Set up, we tin apply the add together() method. However, the insertion order is non retained in the Set up. Internally, for every element, a hash is generated and the values are stored with respect to the generated hash. the values are compared and sorted in ascending order. We need to keep a note that indistinguishable elements are not allowed and all the duplicate elements are ignored. And also, Null values are accepted past the Ready.
Example
Java
import
java.util.*;
class
GFG {
public
static
void
master(Cord[] args)
{
Set<String> hs =
new
HashSet<Cord>();
hs.add(
"B"
);
hs.add(
"B"
);
hs.add(
"C"
);
hs.add together(
"A"
);
Arrangement.out.println(hs);
}
}
Performance 2: Accessing the Elements
Subsequently calculation the elements, if we wish to access the elements, we tin use inbuilt methods like contains().
Example
Coffee
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Gear up<Cord> hs =
new
HashSet<String>();
hs.add together(
"A"
);
hs.add(
"B"
);
hs.add(
"C"
);
hs.add(
"A"
);
System.out.println(
"Ready is "
+ hs);
String check =
"D"
;
System.out.println(
"Contains "
+ check +
" "
+ hs.contains(bank check));
}
}
Output
Ready is [A, B, C] Contains D false
Operation three: Removing the Values
The values tin be removed from the Set using the remove() method.
Example
Java
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Prepare<String> hs =
new
HashSet<Cord>();
hs.add together(
"A"
);
hs.add(
"B"
);
hs.add(
"C"
);
hs.add(
"B"
);
hs.add(
"D"
);
hs.add(
"Eastward"
);
System.out.println(
"Initial HashSet "
+ hs);
hs.remove(
"B"
);
System.out.println(
"After removing chemical element "
+ hs);
}
}
Output
Initial HashSet [A, B, C, D, East] After removing element [A, C, D, Due east]
Operation 4: Iterating through the Set
There are various means to iterate through the Fix. The nearly famous i is to use the enhanced for loop.
Example
Java
import
java.util.*;
form
GFG {
public
static
void
master(String[] args)
{
Set<Cord> hs =
new
HashSet<String>();
hs.add(
"A"
);
hs.add(
"B"
);
hs.add(
"C"
);
hs.add together(
"B"
);
hs.add together(
"D"
);
hs.add(
"E"
);
for
(Cord value : hs)
System.out.print(value +
", "
);
System.out.println();
}
}
Classes that implement the Gear up interface in Java Collections tin can be easily perceived from the image beneath as follows and are listed as follows:
- HashSet
- EnumSet
- LinkedHashSet
- TreeSet
Class 1: HashSet
HashSet class which is implemented in the drove framework is an inherent implementation of the hash tabular array information structure. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let's see how to create a set object using this class.
Example
Coffee
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Set<String> h =
new
HashSet<Cord>();
h.add(
"Republic of india"
);
h.add(
"Commonwealth of australia"
);
h.add together(
"Southward Africa"
);
h.add together(
"Republic of india"
);
System.out.println(h);
h.remove(
"Australia"
);
System.out.println(
"Set after removing "
+
"Australia:"
+ h);
System.out.println(
"Iterating over set:"
);
Iterator<String> i = h.iterator();
while
(i.hasNext())
Organization.out.println(i.next());
}
}
Output
[South Africa, Australia, India] Gear up subsequently removing Commonwealth of australia:[Southward Africa, India] Iterating over set: South Africa India
Class two: EnumSet
EnumSet class which is implemented in the collections framework is one of the specialized implementations of the Set interface for use with the enumeration type. Information technology is a loftier-performance set implementation, much faster than HashSet. All of the elements in an enum set must come up from a single enumeration type that is specified when the set up is created either explicitly or implicitly. Let's come across how to create a ready object using this class.
Case
Java
import
java.util.*;
enum
Gfg { CODE, Larn, CONTRIBUTE, QUIZ, MCQ }
;
public
class
GFG {
public
static
void
main(String[] args)
{
Set<Gfg> set1;
set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
Gfg.Larn, Gfg.CODE);
Organization.out.println(
"Fix ane: "
+ set1);
}
}
Output
Set 1: [CODE, Larn, CONTRIBUTE, QUIZ]
Class three: LinkedHashSet
LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked Listing across all elements. When the iteration guild is needed to exist maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the gild in which they were inserted. Let'southward see how to create a set object using this class.
Example
Java
import
java.util.*;
grade
GFG {
public
static
void
main(String[] args)
{
Gear up<Cord> lh =
new
LinkedHashSet<String>();
lh.add(
"India"
);
lh.add(
"Commonwealth of australia"
);
lh.add together(
"S Africa"
);
lh.add(
"India"
);
System.out.println(lh);
lh.remove(
"Commonwealth of australia"
);
System.out.println(
"Set later on removing "
+
"Australia:"
+ lh);
System.out.println(
"Iterating over set:"
);
Iterator<String> i = lh.iterator();
while
(i.hasNext())
System.out.println(i.next());
}
}
Output
[India, Australia, S Africa] Set after removing Australia:[India, South Africa] Iterating over set: India Due south Africa
Course iv: TreeSet
TreeSet form which is implemented in the collections framework and implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple ready with the exception that it stores elements in a sorted format. TreeSet uses a tree information construction for storage. Objects are stored in sorted, ascending order. Only we tin iterate in descending order using the method TreeSet.descendingIterator(). Let'southward run into how to create a set object using this class.
Example
Java
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Prepare<Cord> ts =
new
TreeSet<Cord>();
ts.add(
"India"
);
ts.add together(
"Commonwealth of australia"
);
ts.add(
"South Africa"
);
ts.add(
"India"
);
Arrangement.out.println(ts);
ts.remove(
"Australia"
);
Arrangement.out.println(
"Set after removing "
+
"Commonwealth of australia:"
+ ts);
System.out.println(
"Iterating over set up:"
);
Iterator<String> i = ts.iterator();
while
(i.hasNext())
System.out.println(i.next());
}
}
Output
[Commonwealth of australia, India, Southward Africa] Set afterward removing Australia:[Bharat, Southward Africa] Iterating over ready: Republic of india South Africa
Source: https://www.geeksforgeeks.org/set-in-java/
0 Response to "How To Get An Element From Set In Java"
Post a Comment