2

I have the following problem:

I have a arraylist called "list" which contains objects of the class "SampleClass", the objects have a property "name". Now I would like to remove a object with a certain "name" value, without knowing the index.

I have tried the following:

list.remove(SampleClass("Village"))

So, the idea would be that the instance of SampleClass where the property name contains "Village" is removed from the list.

It compiles allright, but its not working.

1
  • 1
    maybe you want to turn SampleClass into a data class? Commented May 6, 2020 at 20:06

2 Answers 2

11

If you want to remove all elements with that name, you can use removeAll:

list.removeAll { it.name == "Village" }

If you only want to remove the first item with that name:

If the name is the only property of the class, you should just make it a data class so equals() is based on the name. Then you could use the code you posted.

If it is not the only property, you will have to get the index in the list and remove it that way:

list.removeAt(list.indexOfFirst { it.name == "Village" })
Sign up to request clarification or add additional context in comments.

1 Comment

Also works like a charm, is very quick even for multiple properties and theres no need to override the equals function. Thanks!!
3

The way you have it now, you would have to override the equals method in SampleClass to check if the name property is the same. Right now, it probably doesn't work because the default equals method won't compare the name property and so the SampleClass instance you want to remove with that property as "village" will be considered not equal to the SampleClass instance you're passing in.

Otherwise, you can also use list.filter { it.name != "village" }

2 Comments

An easier way to get a suitable equals() implementation is to make your class a data class (as suggested by Michael Kreutz). The compiler autogenerates equals() for data classes (along with hashCode(), toString(), copy(), and componentN() methods) based on the properties in the constructor.
Making it a data class or overriding the equals function works perfectly! Thanks for pointing me in the right direction!!

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.