Java Collection How to - Add elements to a set which maintains the insertion order








Question

We would like to know how to add elements to a set which maintains the insertion order.

Answer

 /* w  w  w  . j a v  a2 s  . c o m*/

import java.util.LinkedHashSet;

public class Main {
  public static void main(String[] args) {
    LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();
    
    lhashSet.add(new Integer("1"));
    lhashSet.add(new Integer("2"));
    lhashSet.add(new Integer("3"));

    System.out.println(lhashSet);

    boolean blnRemoved = lhashSet.remove(new Integer("2"));

    System.out.println(blnRemoved);
    System.out.println(lhashSet);
  }
}

The code above generates the following result.