Java Collection: LinkedHashSet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Java Collection: LinkedHashSet

Share This

It is an ordered version of HashSet that maintains a doubly-linked List across all elements. We know that in HashSet iteration order is unpredictable, while in LinkedHashSet, we can iterate through the elements in the order in which they were inserted.

A few important facts about LinkedHashMap are as follows:

  1. It contains unique elements.
  2. It maintains insertion order.

Hierarchy of LinkedHashSet class


It extends HashSet and implements Set, Serializable, and Cloneable interfaces in Java.

Source code of Item.java
package com.t4b.test; public class Item { String name; int id; double price; public Item(String name, int id, double price) { super(); this.name = name; this.id = id; this.price = price; } @Override public String toString() { return "Item [name=" + name + ", id=" + id + ", price=" + price + "]"; } }

Source code of TestMain.java
package com.t4b.test; import java.util.Iterator; import java.util.LinkedHashSet; public class TestMain { public static void main(String[] args) { LinkedHashSet<Item> hashset = new LinkedH<Item><Item>(); hashset.add(new Item("Apple", 1, 150.0)); hashset.add(new Item("Grape", 2, 250.0)); hashset.add(new Item("Mango", 3, 10)); hashset.add(new Item("Pine Apple", 4, 100)); Iterator<Item> itr = hashset.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }

Happy Exploring!

No comments:

Post a Comment