LinkedHashSet - insertion order and duplicates - keep newest “on top”

前端 未结 4 2185
离开以前
离开以前 2021-01-01 09:11

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

4条回答
  •  醉酒成梦
    2021-01-01 09:56

    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.

提交回复
热议问题