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

前端 未结 4 2183
离开以前
离开以前 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:02

    All solution provided above are excellent but if we don't want to override already implemented collections. We can solve this problem simply by using an ArrayList with a little trick

    We can create a method which you will use to insert data into your list

    public static  void addToList(List list, T element) {
        list.remove(element); // Will remove element from list, if list contains it
        list.add(element); // Will add element again to the list 
    }
    

    And we can call this method to add element to our list

    List list = new ArrayList<>();
    
    addToList(list, "one");
    addToList(list, "two");
    addToList(list, "three");
    addToList(list, "two");
    

    Only disadvantage here is we need to call our custom addToList() method everytime instead of list.add()

提交回复
热议问题