Remove duplicates from ArrayLists

后端 未结 14 2232
孤街浪徒
孤街浪徒 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条回答
  •  悲哀的现实
    2020-11-27 04:50

    List all = ******** // this is the object that you have already  and filled it.
    List noRepeat= new ArrayList();
    
    for (YourObject al: all) {
        boolean isPresent = false;
        // check if the current objects subtitle already exists in noRepeat
        for (YourObject nr : noRepeat) {
            if (nr.getName().equals(al.getName()) {
                isFound = true;//yes we have already
                break;
            }
        }
    
        if (!isPresent)
            noRepeat.add(al); // we are adding if we don't have already
    }
    

    take one new ArrayList Object of same type
    one by one add all the old arraylists elements into this new arraylist object but before adding every object check in the new arraylist that if there is any object with the same subtitle.if new arraylist contains such subtitle don't add it. otherwise add it

提交回复
热议问题