17

I have created a list of objects and have people added to it:

ArrayList<Person> peeps = new ArrayList<Person>(); 

peeps.add(new Person("112", "John", "Smith"));
peeps.add(new Person("516", "Jane", "Smith"));
peeps.add(new Person("114", "John", "Doe"));

I am trying to figure out how to remove the person from the list by ID number. So if I wanted to remove the person with the ID number 114 but didn't now where it fell in the list, how would I?

Zong
  • 6,160
  • 5
  • 32
  • 46
NLMDEJ
  • 385
  • 1
  • 3
  • 14
  • 5
    Do you have to use an ArrayList? You would be much better off with a HashMap. – lacraig2 Mar 17 '15 at 18:56
  • 2
    You haven't chosen the right data structure for your problem. Use a `Map`, not a `List`. – Asaph Mar 17 '15 at 18:57
  • Can you extend your Person class? – ddagsan Mar 17 '15 at 18:58
  • @lacraig2 `Map` – m0skit0 Mar 17 '15 at 19:07
  • @m0skit0 true. Would be a string. Its a bit weird to store integers like that, but it is a string. – lacraig2 Mar 17 '15 at 19:11
  • @lacraig2 I thought so at first too, but if you think about it, it's not really weird. These are IDs, you aren't going to perform numeric operations on them, so there's no reason to treat them as numbers. By declaring them as String you make this clear. You might also wanna have a "001" ID, which you cannot store using a number. – m0skit0 Mar 17 '15 at 19:24

7 Answers7

49

Using Java8:

peeps.removeIf(p -> p.getId().equals("112"));

Note that this is equivalent to linear search and will take O(n) time. If this operation will be repeated frequently it is recommended to use a HashMap in order to speed things up to O(1).

Alternatively using a sorted list would also do the trick, but require O(log n) time.

13

If you are going to be using an ArrayList, the the only way is to go through the entire list, looking at each person, and seeing it their id number is 114. For larger datasets, this is not going to efficient and should be avoided.

If you can change your data structure, then some sort of Map would be better (HashMap is typically a good choice). You could have the id number as a "key" and then associate it with each person. Later you can query the Map by key. The con is you can only have one value as a key, so you can't have say both name and id number keys

Edit:
An more efficient way to do use an ArrayList would be to keep it sorted by id number. Then you can use something like Collections.binarySearch() to quickly access the elements by id number. The con is is that it is expensive to remove from/insert into a sorted array, as everything greater the element has to be moved. So if you are going to be doing relatively few changes compared to the number of reads, this might be viable

vandale
  • 3,600
  • 3
  • 22
  • 39
7

There are many ways to tackle this.

  1. I am using CollectionUtils from apache.common.collection4 or its google equivalent. and then select what you wish using a predicate or in java 8 an lambda expression.
CollectionUtils.select(peeps, new Predicate<Person>() {
    @Override
    public boolean evaluate(Person object) {
        return object.getId().equals("114");
    }
});
  1. use good old iterator and loop over it
Iterator<Person> iterator = peeps.iterator();
while(iterator.hasNext()) {
   Person next = iterator.next();
   if(next.getId().equals("114")) {
       iterator.remove();
   }
}
Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
Noam Shaish
  • 1,613
  • 2
  • 16
  • 37
3

iterate in the ArrayList elements and remove the ones which match the string you want to remove: The Iterator remove operations is safe and does not create a ConcurrentModificationException

for (Iterator<String> iterator = peeps.iterator(); elementToCheck = iterator.next();) {
    if (elementToCheck.getId().equals("112")) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}
adrCoder
  • 3,145
  • 4
  • 31
  • 56
3

You first need to have a working equals in your Person class (which you should). Then you can just use List#indexOf and List#remove. For example:

final Person toRemove = new Person("112");
peeps.remove(peeps.indexOf(toRemove));

(assuming the Person ID is unique).

Alternatively if your list is an ArrayList you can use ArrayList#remove(Object):

final Person toRemove = new Person("112");
peeps.remove(toRemove);

If you're using Java 8, you can use Paul's solution.

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

if you want to search for string then should use .equals

String query;
ArrayList<String> list;

   for(int i=0; i < list.size();i++)
       if (list.get(i).equals(query)){
           list.remove(i);
           break;
       }
-1
class Processor{

ArrayList<Person> peeps = new ArrayList<Person>(); 

void setPeeps(){
    peeps.add(new Person(112, "John", "Smith"));
    peeps.add(new Person(516, "Jane", "Smith"));
    peeps.add(new Person(114, "John", "Doe"));
}

void removePerson(int id){
    for(int i=0; i <= peeps.size(); i++){
        Person person = peeps.get(i);
        if(person.id == id)
            peeps.remove(peeps.get(i));
    }
}

void displayPersonsList(){
    for(Person person : peeps){
        System.out.println(person.id + ":" + person.fName + ":" + person.lName);
    }
}

public static void main(String args[]){
    Processor objProcessor = new Processor();
    objProcessor.setPeeps();
    objProcessor.removePerson(114);
    objProcessor.displayPersonsList();
}
}

class Person{
int id;
String fName;
String lName;

public Person(int id, String fName, String lName){
    this.id = id;
    this.fName = fName;
    this.lName = lName;
}
}
Jobin Thomas
  • 111
  • 1
  • 8
  • I did not just type the code in here. I tried it on STS, ran it and then copied it. Can you post your error here? I tried it again, it works! – Jobin Thomas Mar 18 '15 at 13:19
  • @JobinThomas try removing any entry but the last one! (assuming you are still reading the site) – user85421 Jan 22 '17 at 18:58