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

前端 未结 4 2151
离开以前
离开以前 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 10:03

    When initializing you're LinkedHashSet you could override the add method.

    Set set = new LinkedHashSet(){
        @Override
        public boolean add(String s) {
            if(contains(s))
                remove(s);
            return super.add(s);
        }
    };
    

    Now it gives you:

    set.add("1");
    set.add("2");
    set.add("3");
    set.add("1");
    set.addAll(Collections.singleton("2"));
    
    // [3, 1 ,2]
    

    even the addAll method is working.

提交回复
热议问题