简体   繁体   中英

How to find a specific value inside an ArrayList and edit it

I have an ArrayList of my Item class, the Item class contains 5 String variables (let's say id , name , surname , email , city ), after I initialize my ArrayList I want to parse it. What I want is:

I have a String x = "123" and I want to find the item that contains this id and then be able to edit it, how can I possibly do it?

I found that there's a method MyList.contains(ItemExample) but with this method I have to pass an Item that contains every variable not just the id.

EDIT:

for (int i = 0; i < MyList.size(); i++) {
            System.out.println(MyList.get(i)); //for example I want to print ONLY the id, not the other variables inside MyList
        }

There can be 2 approaches which you can use in order to do what you want :-

  1. If your id is unique for all Item objects you can use Map<String, Item> , where key would be your id and value would be your Item object.

    Map<String, Item> map = new HashMap <String, Item>(); map.put(ID, new Item()); String idToSearch = ID_SEARCHED; Item searchedItem = map.get(ID_SEARCHED); if(searchedItem != null) searchedItem .setId(NEW_ID); else System.out.println("Item not found);"

  2. If id is not unique, then you need to use only List and need to iterate over whole list in order to first get the object, then second set the new value.

    List<Item> items = new ArrayList<Item>(); items.add(new Item()); String idToSearch = ID_SEARCHED; for(Item singleItem : items){ if(singleItem.getId().equals(ID_SEARCHED;)){ singleItem.setId(NEW_ID); } }

PS:- In 2nd Way, all the Item object's id will be updated , which are having id as ID_SEARCHED

You can iterate over the list.

Or better if the retrieve by id is a frequent operation replace the list with a Map. A map is a collection of pair Key Value and you can access the value using the key with a method get(key).

So your code become:

Map<String, Item> map = ....

String idTosearch = ....
Item item = map.get(idTosearch);

refer below example according to your scenario

import java.util.*;  
public class TestStudent{  

    // find student by ID and modify it
    public void findStudentByID(ArrayList al, int id){

        Iterator itr=al.iterator();    
        while(itr.hasNext()){  
            Student st=(Student)itr.next();
            if(st.rollno==id){   
                st.age=20;
                st.name="Singh";
            }

        } 
    }

    public void showStudents(ArrayList al){
        Iterator itr=al.iterator();    
        while(itr.hasNext()){  
            Student st=(Student)itr.next();  
            System.out.println(st.rollno+" "+st.name+" "+st.age);  
        } 
    }


    public static void main(String args[]){  
        //Creating user-defined class objects  
        Student s1=new Student(101,"Girdhar",23);  
        Student s2=new Student(102,"Rathore",21);  
        Student s3=new Student(103,"Banna",25);  

        ArrayList<Student> al=new ArrayList<Student>();//creating arraylist  
        al.add(s1);//adding Student class object  
        al.add(s2);  
        al.add(s3);  

        TestStudent obj=new TestStudent();
        //show before modifiying
        obj.showStudents(al);

        //update student
        obj.findStudentByID(al, 102);

        //show after modifiying
        obj.showStudents(al);

    }  
}  

class Student{  
    int rollno;  
    String name;  
    int age;  
    Student(int rollno,String name,int age){  
        this.rollno=rollno;  
        this.name=name;  
        this.age=age;  
    }  

}  

You can give a try to map as follow:

import java.util.HashMap;

public class SordidSort {

    public static void main(String args[]) {
        //Use the map
        HashMap<String, Item> itemMap = new HashMap<String, Item>();

        //Create & Add the Item Objects to map with key as id value in Object
        // Like
        Item item = new Item();
        item.id = "123";
        itemMap.put(item.id, item);

        //update id value
        String x = "123";

        if(itemMap.containsKey(x)){
            Item serachedItem = itemMap.get(x);
            if(serachedItem != null){
                serachedItem.id = "321"; // new Id
                itemMap.put(serachedItem.id, serachedItem); // Put Item Back to Map
                itemMap.remove(x); // Remove old Item from Map , this is required if id is changed. not requred if other values changed.
            }
        }
    }
}
class Item{
    //Your attributes
    String id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM