Prasad Jandrajupalli
Prasad Jandrajupalli

Reputation: 59

How to display HashSet objects in preserve order?

Basically HashSet following insertion order is not preserved, but I want to display HashSet objects in the form of preserve order in Java.

Is it possible? If yes then can you please share some ideas.

Thanks in advance

JP.

Upvotes: 1

Views: 163

Answers (5)

Amit Kumar user3037405
Amit Kumar user3037405

Reputation: 390

Use LinkedHashSet it preserves the order of insertion.

Set<String> set = new LinkedHashSet<String>();
    for(int i = 0; i <5; i++)
    {
        set.add( i+"" );
    }
    // insertion order is 0,1,2,3,4
    for(String str : set)
    {
        System.out.println(str);
    }

    //output 0,1,2,3,4

Upvotes: 0

CrisIf
CrisIf

Reputation: 36

If the order of insertion is important, maybe you should use an ArrayList.

Upvotes: 1

Tim B
Tim B

Reputation: 41188

For Set there is LinkedHashSet and for Map there is LinkedHashMap - both retain the order in which items were inserted although there is a very small performance impact.

There is also the option of TreeMap and TreeSet which do not retain the order in which elements were inserted but instead keeps them in a specified order (either their natural ordering or as specified by a comparator).

Upvotes: 1

Chris Mantle
Chris Mantle

Reputation: 6683

You can use LinkedHashSet, which preserves insertion order.

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Use LinkedHashSet instead of HashSet. LinkedHashSet will maintain the insertion order.

Upvotes: 4

Related Questions