Remove object from ArrayList with some Object property

Viewed 33251

I am maintaining one ArrayList of objects. And my object structure is Id, name, some other details. I need to remove one the object with some id value say(10) and I don't want to iterate over the list. Is there any solution for this?

5 Answers

Maybe I don't understand the question but why nobody suggested to use override equals and hashcode for that user class?

class MyObject {
    final String id;
    final String name;

    MyObject(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        return Objects.equals(id, ((MyObject) o).id);
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }

    @Override
    public String toString() {
        return "MyObject{id='" + id + "', name='" + name + "'}";
    }
}

in this case you can easy remove any object from list

        final ArrayList<MyObject> list = new ArrayList<>();
        list.add(new MyObject("id1", "name1"));
        list.add(new MyObject("id2", "name2"));
        list.add(new MyObject("id3", "name3"));

        MyObject removeCandidate = new MyObject("id2", "name2");

        list.remove(removeCandidate);
        System.out.println(list);

code above prints

[MyObject{id='id1', name='name1'}, MyObject{id='id3', name='name3'}]
Related