I need a collection that keeps insertion order and has unique values. LinkedHashSet looks like the way to go, but there\'s one problem - when two items are equal, it removes
You can simply use a special feature of LinkedHashMap:
Set set = Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true));
set.add("one");
set.add("two");
set.add("three");
set.add("two");
System.out.println(set); // prints [one, three, two]
In Oracle’s JRE the LinkedHashSet is backed by a LinkedHashMap anyway, so there’s not much functional difference, but the special constructor used here configures the LinkedHashMap to change the order on every access not only on insertion. This might sound as being too much, but in fact affects the insertion of already contained keys (values in the sense of the Set) only. The other affected Map operations (namely get) are not used by the returned Set.
If you’re not using Java 8, you have to help the compiler a bit due to the limited type inference:
Set set
= Collections.newSetFromMap(new LinkedHashMap(16, 0.75f, true));
but the functionality is the same.