Set

From Rasim SEN - Knowledge Base/Java/Springframework/Microservices/Cloud-AWS/AI
Jump to: navigation, search

The java.util.Set interface is a subtype of the java.util.Collection interface. It represents set of objects, meaning each element can only exists once in a Set.

Java Set Example

Set setA = new HashSet();

String element = "element 1";

setA.add(element);

System.out.println( setA.contains(element) );

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


EnumSet

HashSet

HashSet is backed by a HashMap. It makes no guarantees about the sequence of the elements when you iterate them.

LinkedHashSet

LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet. Reinserting an element that is already in the LinkedHashSet does not change this order.

TreeSet

TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a Collections.sort() on a List or array containing these elements. This order is determined either by their natural order (if they implement Comparable), or by a specific Comparator implementation.


There are also Set implementations in the java.util.concurrent package

Here are a few examples of how to create a Set instance:

Set setA = new EnumSet();
Set setB = new HashSet();
Set setC = new LinkedHashSet();
Set setD = new TreeSet();


Adding and Accessing Elements

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


Set setA = new HashSet();

setA.add("element 1");
setA.add("element 2");
setA.add("element 3");

The three add() calls add a String instance to the set.

When iterating the elements in the Set the order of the elements depends on what Set implementation you use, as mentioned earlier. Here is an iteration example:


Set setA = new HashSet();

setA.add("element 0");
setA.add("element 1");
setA.add("element 2");

//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : setA) {
    String element = (String) object;
}


Removing Elements

You remove elements by calling the remove(Object o) method. There is no way to remove an object based on index in a Set, since the order of the elements depends on the Set implementation.


Generic Sets

By default you can put any Object into a Set, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a Set. Here is an example:


Set<MyObject> set = new HashSet<MyObject>();

This Set can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:


for(MyObject anObject : set){
   //do someting to anObject...
}


For more information about Java Generics, see the Java Generics Tutorial


Collection Example:

package com.oasissofttech.collections.study;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionTests {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("var 1");
		list.add("var 2");
		list.add("var 3");
		list.add("var 4");
		list.add("var 1");
		list.remove("var 3");
		System.out.println("List:");
		System.out.println(list);
		System.out.println("list count:"+list.size());
		
		Set set = new HashSet();
		set.add("set 1");
		set.add("set 2");
		set.add("set 3");
		set.add("set 4");
		set.remove("set 1");
		
		System.out.println("Set:");
		System.out.println(set);
		System.out.println("set count:"+set.size());
		
		
		Map map = new HashMap();
		map.put(1, "map 1");
		map.put(2, "map 2");
		map.put(3, "map 3");
		map.put(4, "map 4");
		map.put(5, "map 5");
		map.remove(3);
		
		System.out.println("Map:");
		System.out.println(map);
		System.out.println("map count:"+map.size());

		
	}
}

output:

List:
[var 1, var 2, var 4, var 1]
list count:4
Set:
[set 2, set 3, set 4]
set count:3
Map:
{1=map 1, 2=map 2, 4=map 4, 5=map 5}
map count:4