Java Language Sets Initialization

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

Set have its implementation in various classes like HashSet, TreeSet, LinkedHashSet.

For example:

HashSet:

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

Here T can be String, Integer or any other object. HashSet allows for quick lookup of O(1) but does not sort the data added to it and loses the insertion order of items.

TreeSet:

It stores data in a sorted manner sacrificing some speed for basic operations which take O(lg(n)). It does not maintain the insertion order of items.

TreeSet<T> sortedSet = new TreeSet<T>();

LinkedHashSet:

It is a linked list implementation of HashSet Once can iterate over the items in the order they were added. Sorting is not provided for its contents. O(1) basic operations are provided, however there is higher cost than HashSet in maintaining the backing linked list.

LinkedHashSet<T> linkedhashset = new LinkedHashSet<T>();


Got any Java Language Question?