Remove duplicates from ArrayLists

后端 未结 14 2201
孤街浪徒
孤街浪徒 2020-11-27 04:12

I have an ArrayList of custom objects. I want to remove duplicate entries.

The objects have three fields: title, subtitle, and id. If a su

14条回答
  •  Happy的楠姐
    2020-11-27 04:48

    List result = new ArrayList();
    Set titles = new HashSet();
    
    for(Item item : originalList) {
        if(titles.add(item.getTitle()) {
            result.add(item);
        }
    }
    

    add() of the Set returns false if the element already exists.

提交回复
热议问题