Search code examples
javacollectionshashsetlinkedhashset

Is there any way to get the items from HashSet in insertion order in java?


Our existing code using HashSet to store data's.I know Nature of the Set interface is giving random order.But i need the same insertion order.Is there any way to get the insertion order from the set???

Please guide me get out of this issue?

I also used LinkedHashSet, it also giving elements in some other order and not insertion order that i wanted...

Set attachmentSet=new HashSet();
        attachmentSet.add("dfsdfsd");
        attachmentSet.add("erwerwer");
        attachmentSet.add("vcvcvcv");
        attachmentSet.add("ytytyt");

        Iterator attachItr=attachmentSet.iterator();
        while(attachItr.hasNext())
        {
            System.out.println("SET Item::"+attachItr.next());
        }

LinkedHashSet newCopy = new LinkedHashSet();
        newCopy.add("dfsdfsd");
        newCopy.add("erwerwer");
        newCopy.add("vcvcvcv");
        newCopy.add("ytytyt");
        Iterator attachItr2=copy.iterator();
        while(attachItr2.hasNext())
        {
            System.out.println("NEW LinkedHashSet Item::"+attachItr2.next());
        }

Solution

  • I would say that it is not possible because of the way hash set works:

    When you insert something into a hash set, its hash is computed (a special unique value obtained through some maths) and it is then stored as a mapping from its hash to its value. No 'history' of insertion is kept.

    If you do want to achieve what you describe, you better choose another data structure such as a linked list.

    Edit: as suggested by llogiq and Sasikumar Murugesan, a good data structure that could fit your needs and keep the rest of your software as is would be to use a LinkedHashSet. This allows your software to still use HashSet elsewhere.