Java Tutorial Series - Collections -Sets
Having covered ArrayList, LinkedList, HashMap, LinkedHashMap, TreeMap, we have come with another Collection called Sets. It is one of the dominant collection.
Sets is a kind of collection that only stores unique elements.
Sets is a kind of collection that only stores unique elements.
Syntax of Set
Set<String> ele = new HashSet<String>();
ele.add("Apple");
ele.add("Banana");
ele.add("Orange");
ele.add("Watermelon");
ele.add("Grapes");
System.out.println(ele);
//Output - [Apple, Grapes, Watermelon, Orange, Banana]
- HashSet doesn't retain any order.
- LinkedHashSet remembers the order elements are inserted.
- TreeSet sorts the elements in natural order.
How to iterate through each element in Sets using for each loop -
for (String element : ele) {
System.out.println(element) ;
}
Another awesome feature of using Set is we can search for a particular element and perform some action, for example -
If(ele.contains("Orange") {
System.out.println("Orange found!!!");
}
There are lot of awesome methods under Set Interface that can be used and applied to our day to day task. Click here to learn more.
Consider a scenario where you might have 2 different Sets and you want to find common elements present in both the sets, how would you do it? This is an interview question which is often asked to test your ability, let's find out below.
System.out.println(common);
Let's think other way around now, we were able to find the common elements from both the sets, what if we want to find out the unique elements in each sets. Let's see in the below example -
Set<String> difference = new Set<String>(ele1);
difference.removeAll(ele);
System.out.println(difference);
That's it from Sets one needs to know about! We hope you liked and understood it.
Happy Learning and Happy Sharing!
There are lot of awesome methods under Set Interface that can be used and applied to our day to day task. Click here to learn more.
Consider a scenario where you might have 2 different Sets and you want to find common elements present in both the sets, how would you do it? This is an interview question which is often asked to test your ability, let's find out below.
Set<String> ele1 = new HashSet<String>();
ele1.add("Flower");
ele1.add("Mango");
ele1.add("Strawberry");
ele1.add("Orange");
ele1.add("Grapes");
Set<String> common = new Set<String>(ele1);
common.retainAll(ele);
System.out.println(common);
Let's think other way around now, we were able to find the common elements from both the sets, what if we want to find out the unique elements in each sets. Let's see in the below example -
Set<String> difference = new Set<String>(ele1);
difference.removeAll(ele);
System.out.println(difference);
That's it from Sets one needs to know about! We hope you liked and understood it.
Happy Learning and Happy Sharing!
Comments
Post a Comment