and should be unique
A Set
implementation contains no duplicate elements, as explained in more detail in the Javadoc.
java collection to retain order
What do you mean by "order"?
Insertion-order: LinkedHashSet
If you mean tracking the order in which the objects were originally added to the set, use LinkedHashSet
.
Set< String > colors = new LinkedHashSet<> () ;
String peachPuff = "PeachPuff" ;
colors.add( "CornflowerBlue" ) ;
colors.add( peachPuff ) ;
colors.add( "DarkSlateGray" ) ;
colors.add( peachPuff ) ; // Adding again. Original insertion order maintained.
Run code live at IdeOne.com. Notice how peachPuff
object remains in its original # 2 position despite being added to the set a second time.
System.out.println( "colors.toString(): " + colors ) ;
colors.toString(): [CornflowerBlue, PeachPuff, DarkSlateGray]
Sorted-order: TreeSet
or ConcurrentSkipListSet
If you mean keeping the elements sorted by their content, use an implementation of NavigableSet
(successor to SortedSet
).
The sorting is done either by:
Two classes bundled with Java implement NavigableSet
(and SortedSet
): TreeSet
& ConcurrentSkipListSet
.
TreeSet
If you manipulating the set within a single thread, or only using the set across threads for reads only, use TreeSet
.
Example:
Set< String > names = new TreeSet<> () ;
names.add( "Carol" ) ;
names.add( "Alice" ) ;
names.add( "Bob" ) ;
This will be reported in alphabetical order. See this code run live at IdeOne.com.
names.toString(): [Alice, Bob, Carol]
ConcurrentSkipListSet
If manipulating the set across threads, concurrency is an issue. Use ConcurrentSkipListSet
class.
You may want to learn about the skip list algorithm.
Enum definition order: EnumSet
If you want to track a collection enum objects (see Tutorial) by the order in which they are defined on the enum, use EnumSet
. This class is highly optimized for enums, being very fast to execute and using very little memory.
Example: Track the weekend days from the DayOfWeek
enum.
Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SUNDAY , DayOfWeek.SATURDAY ) ;
Despite our defining the set in wrong order, the EnumSet
will iterate the items in the order defined on the DayOfWeek
enum. That order is Monday-Sunday, so our EnumSet
will iterate with Saturday reporting before Sunday.
See this code run live at IdeOne.com.
weekend.toString(): [SATURDAY, SUNDAY]