In this post, we will see about LinkedHashSet in java. LinkedHashSet is same as HashSet except that it maintains insertion order.
Some points about LinkedHashSet
- LinkedHashSet implements Set interface and extends HashSet class.
- LinkedHashSet maintains insertion order, so when you will be able to access elements in the order they were inserted like ArrayList.
Example:
LinkedHashSetMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; import java.util.LinkedHashSet; public class LinkedHashSetMain { public static void main(String args[]) { // LinkedHashSet with Country // LinkedHashSet maintains insertion order LinkedHashSet<String> countryHashSet=new LinkedHashSet<String>(); countryHashSet.add("India"); countryHashSet.add("Japan"); countryHashSet.add("France"); countryHashSet.add("Russia"); countryHashSet.add("India"); countryHashSet.add("France"); countryHashSet.add("United Kingdom"); System.out.println("-----------------------------"); System.out.println("Iterating LinkedHashSet"); System.out.println("-----------------------------"); for (String country:countryHashSet) { System.out.println(country); } System.out.println("-----------------------------"); } } |
1 2 3 4 5 6 7 8 9 10 11 |
----------------------------- Iterating LinkedHashSet ----------------------------- India Japan France Russia United Kingdom ----------------------------- |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.