15

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?

0

5 Answers 5

63

Using Java-8 Collection#removeIf

myList.removeIf(obj -> obj.id == 10);

With Java-7 you'll have to use iterator:

for(Iterator<MyType> iterator = myList.iterator(); iterator.hasNext(); ) {
    if(iterator.next().id == 10)
        iterator.remove();
}

Note that list iteration is necessary in any case. In Java-8 removeIf method it's just performed internally.

Sign up to request clarification or add additional context in comments.

4 Comments

@Tagir Valeev Thanks a lot for ur valid reply.Is there any way without Iterate???
@django Check the Java-8 possibility.
Both of these involve iterating over the list.
@Tagir Valeev ..Ya It is working. One more doubt Istead of remove I need to get that object with id=10. what shud I do?
3

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'}]

Comments

2

If you really do not want to iterate over the list, you could use a stream but I personnally prefer Collection#removeIf like @TagirValeev suggested

myList = myList.stream()
               .filter(x -> x.id() != 10)
               .collect(Collectors.toList());

Comments

1

It is not possible1 to remove instances of an element from an ArrayList without iterating the list in some way2. The ArrayList is an array under the hood, and you need to examine each element in the array to see whether it matches the criteria for removal. At the fundamental level, that entails a loop ... to iterate over the elements.

Also note that when you remove a single element from an array, all elements with positions after the removed elements need to be moved. On average, that will be half of the array elements.

Now, you can code these operations in ways that avoid you using an explicit for loop, but the iteration will be happening behind the scenes, no matter how you code it.


1 - Not strictly true. Hypothetically, if you had a separate data structure that (for instance) mapped values to the indexes of elements in the ArrayList, then you could remove the elements without iterating. But I can't see how you could manage that data structure efficiently.

2 - Iteration doesn't just mean using an Iterator. For loops, Stream, Collections.removeIf and other solutions all entail iterating the elements of the list under the hood.

Comments

0

You could not do that without iterator, you should you Hashmap for this.

public class ObjectStructure{
private int Id;
private String name;
//and any data field you need
}

generate all setters and getters.

Use this class in

Hashmap<Integer, ObjectStructure> data = new HashMap<>();

you can add and delete data with only key which is Integer.

data.remove(10);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.