Java Set
Set

Java Set

Overview

The Set interface is present in java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

For official documentation on Set please refer oracle docs

Java Set vs List

  • the same element cannot occur more than once in a Java Set. This is different from a Java List where each element can occur more than once.
  • The elements in a Set has no guaranteed internal order. The elements in a List has an internal order, and the elements can be iterated in that order.

Java Set Example

Here is the example program for creating a Set

package com.techijournal.sets;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetExample {
	public static void main(String[] args) {
		int count[] = { 5, 10, 15, 60, 65, 70 };
		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) {}
	}
}
Output
[65, 5, 10, 60, 15]
The sorted list is:
[5, 10, 15, 60, 65]
The First element of the set is: 5
The last element of the set is: 65

Methods & Description

Sr.No.Method & Description
1add( )Adds an object to the collection.
2clear( )Removes all objects from the collection.
3contains( )Returns true if a specified object is an element within the collection.
4isEmpty( )Returns true if the collection has no elements.
5iterator( )Returns an Iterator object for the collection, which may be used to retrieve an object.
6remove( )Removes a specified object from the collection.
7size( )Returns the number of elements in the collection.

Set Implementations

Being a Collection subtype all methods in the Collection interface are also available in the Set interface.

Since Set is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Set implementations in the Java Collections API:

  • java.util.EnumSet
  • java.util.HashSet
  • java.util.LinkedHashSet
  • java.util.TreeSet

Each of these Set implementations behaves a little differently with respect to the order of the elements when iterating the Set, and the time (big O notation) it takes to insert and access elements in the sets.

Add Element to Set

To add elements to a Set, call its add() method. This method is inherited from the Collection interface. Here are a few examples:

Set<String> setA = new HashSet<>();
setA.add("TechiJournal 1");
setA.add("TechiJournal 2");
setA.add("TechiJournal 3");

Iterate Set Using Iterator

To iterate the elements of a Set using an Java Iterator, you must first obtain an Iterator from the Set. You obtain an Iterator from a Set by calling the iterator() method. Here is an example of obtaining an Iterator from a Set:

Set<String> techSet = new HashSet<>();
techSet.add("TechiJournal 1");
techSet.add("TechiJournal 2");
techSet.add("TechiJournal 3");
Iterator<String> iterator = set.iterator();
while(iterator.hasNext(){
  String element = iterator.next();
}

Iterate Set Using the Java Stream API

To iterate a Java Set using the Java Stream API you must create a Stream from the Set. Here is an example of creating a Java Stream from a Set and iterate the Stream:

Set<String> set = new HashSet<>();
set.add("abc");
set.add("cde");
set.add("efg");
Stream<String> stream = set.stream();
stream.forEach((element) -> { System.out.println(element); });

Remove Elements From Set

Elements from a Java Set can be removed by calling the remove(Object o)method. Here is an example of removing an element from a Java Set:

set.remove("object-to-remove");

Remove All Elements From Set

All the elements from a Java Set can be removed using the clear() method which is shown below

set.clear();

Convert Java Set to List

Java Set can be converted to a Java List by creating a List and calling its addAll() method, passing the Set as parameter to the addAll() method. Here is an example of converting a Java Set to a List:

Set<String> set = new HashSet<>();
set.add("123");
set.add("456");
List<String> list = new ArrayList<>();
list.addAll(set);

Conclusion

There is a lot more you can do with a Set which will be discussed in further posts. A Set is a Collection that cannot contain duplicate elements.

Thanks, Note

Thanks for spending your valuable time reading this post. Hope this post taught you something new today. Please share the post if you like it.

Sumanth Patnaikuni

Hi Guys. I am a technology enthusiast always try to learn new things. So I decided to share my knowledge through this platform. I worked for several companies and having 4+ years of experience. as full stack developer. Please leave your comments if there is any doubt regarding the blog. And also please recommend me if you require any particular topic so that I can guide you through my blog.

This Post Has 15 Comments

  1. sikis

    Appreciating the persistence you put into your site and detailed information you offer. Marleah Garner Connell

  2. erotik

    Sweet internet site , super pattern , really clean and apply pleasant. Sofie Grace Starbuck

  3. bahis

    I am genuinely grateful to the holder of this site who has shared this wonderful article at at this time. Anthea Mickey Almeria

  4. sikis

    Merely wanna admit that this is very helpful, Thanks for taking your time to write this. Philipa Lutero Cristabel

  5. erotik

    Everything is very open with a precise description of the issues. It was really informative. Your site is very useful. Many thanks for sharing. Latrina Nikolas Ramsden

  6. torrent

    Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is really good. Luci Moe Vito

  7. bedava

    I have been exploring for a little for any high quality articles or weblog posts on this sort of house . Constantina Glenn Kant

  8. torrent

    Hi, its good post concerning media print, we all understand media is a wonderful source of information. Grier Alic Alvera

  9. download

    The facts mentioned within the post are a number of the most beneficial accessible. Daryn Jessie Carnahan

  10. download

    At this time I am going away to do my breakfast, when having my breakfast coming over again to read additional news. Dolores Ephrayim Rai

  11. indir

    I got what you mean,saved to bookmarks, very decent website. Celka Xever Ida

  12. torrent

    Thank you your video is very helpful looking forward to watching the next one. Babbie Ari Daberath

  13. yify

    Wow! I cant think I have found your weblog. Very useful information. Ginni Clifford Countess

  14. bluray

    Excellent article. I will be going through some of these issues as well.. Vanny Haskel Amabelle

Leave a Reply