Sobes.tech
Junior — Middle

Is there a data structure that combines the properties of a hash table and element ordering?

sobes.tech AI

Answer from AI

Yes, such a data structure exists. In Java and Android, it is called LinkedHashSet — it combines the properties of a hash table and maintains the insertion order of elements.

LinkedHashSet stores elements uniquely (like HashSet) and preserves the order of their addition, allowing iteration in the same order.

Example of using LinkedHashSet:

LinkedHashSet<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("one");
linkedSet.add("two");
linkedSet.add("three");

for (String s : linkedSet) {
    System.out.println(s); // Will output: one, two, three
}

If you need sorting by natural order, you can use TreeSet, but it is not based on a hash table.

Is there a data structure that combines the… - sobes.tech