Java - Set (Collection)

Java Conceptuel Diagram

About

This interface is a member of the Java Collections Framework.

Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine.

See java.util.Set

Using a HashSet, contains is a constant-time operation. This is much better than a linear search through an array.

Restrictions / Prerequisites

  • The Set collection doesn't allow duplicate and use the equals and hashCode methods to ensure this integrity. This methods must be then implemented in the element of your collection.
  • It is not permissible for a set to contain itself as an element.
  • The behaviour of a set is not specified with mutable objects as element. (If the value of an object is changed in a manner that affects equals comparisons).

Methods

Basic Methods

int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element);  // optional
boolean remove(Object element); // optional
Iterator<E> iterator();

Bulk Methods

boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); // optional
boolean removeAll(Collection<?> c);  // optional
boolean retainAll(Collection<?> c); // optional
void clear(); // optional

Array Methods

Object[] toArray();
<T> T[] toArray(T[] a);

Management

Creation

New

The Java platform contains three general-purpose Set implementations:

It stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.

Set<String> myHashSetMap= new HashSet<String>();
// or with a initial set
Set<String> set = new HashSet<>(Arrays.asList("first element"));
// or
Stream.of("a", "b").collect(Collectors.toSet());
  • TreeSet,

It stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.

  • LinkedHashSet.

It is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher.

  • SortedSet

a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

From Stream with a constructor

  • Collectors.toSet() for a HashSet
mySet = Arrays.stream(conf.split(","))
        .map(String::trim)
        .collect(Collectors.toSet());
  • For a specific set, Collectors.toCollection
mySet = Arrays.stream(conf.split(","))
        .map(String::trim)
        .collect(Collectors.toCollection(SetKeyIndependent::new));

Remove a key

mySet.remove(myKeyObject)

To list

Java - List (sequence)

  • from list instantiation
List<T> ts = new ArrayList<T>(mySet);
//or
List<T> ts = new ArrayList<T>();
ts.addAll(mySet)
List<String> list = set.stream().collect(Collectors.toList());

How to

Get no Duplicate in a set

As a Set which, by definition, cannot contain a duplicate, the function works by using the standard conversion constructor described in the The Collection Interface section.

The equals and hashCode methods must be implemented.

If you have a Collection c where you want to eliminate all duplicates.

  • In on line
Collection<Type> noDups = new HashSet<Type>(c);
// of to preserve the order of the original collection
Collection<Type> noDups = new LinkedHashSet<Type>(c);
  • With a method:
public static <E> Set<E> removeDups(Collection<E> c) {
    return new LinkedHashSet<E>(c);
}

Documentation / Reference





Discover More
Java Conceptuel Diagram
Generic

and Integer.class is of type Class Stronger type checks at compile time. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find. The compiler can check the type...
Java Collection Type
Java - (Collection|container) Framework (Types)

A collection (known also as a container) is an object that groups multiple objects (elements) into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. ...
Java Conceptuel Diagram
What does the equals method in Java?

The equals method is the the equality operator. hashCode() . In a set implementation, it's used to be sure that there will be no duplicate objects.



Share this page:
Follow us:
Task Runner