Replace element of ArrayList if object of same value already present in it

java update arraylist object
replace element in arraylist java
java 8 replace object in list
java 8 update object in list
replace element in array java
shifting arraylist elements in java
java replace item in list while iterating
which of the following would you use to change the arraylist element at position i to e

I'm using socket.io for my chat app. I have an ArrayList which contains last message, username, time. Whenever a new message arrives in JSON format then it should check if JSON contained username is present in ArrayList or not. If present, then updates the ArrayList otherwise add in ArrayList. Here is my code:-

private Emitter.Listener handle1 = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        ChatLists.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                JSONObject data = (JSONObject)args[0];
                try {
                    String sendername = data.getString("sender");
                    String lastMessage = data.getString("message");
                    String profileImage = data.getString("Profile");
                    String token = data.getString("fb_token");
                    chat_list chat_list = new chat_list(sendername,
                            profileImage, lastMessage, "0", "", "dummy", token);


                    if (chat_lists.size()==0){
                        chat_lists.add(chat_list);
                    }else {
                        for (int i=0;i<chat_lists.size();i++){
                            if (chat_lists.get(i).getContactname().equals(sendername)){
                                chat_lists.set(i,chat_list);
                            }else {
                                chat_lists.add(chat_list)
                            }
                        }

                    }
                    contactlistAdapter = new ContactlistAdapter(chat_lists);
                    recyclerView.setAdapter(contactlistAdapter);
                    contactlistAdapter.notifyDataSetChanged();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }
        });
    }
};

Well, you can use contains() & set() methods of ArrayList in a logical way to solve your problem like below:-

if(chat_lists.contains(username)) 
 chat_lists.set(indexOf(username), new_username);

else chat_lists.add(new_username);

Replace element of ArrayList if object of same value already present , To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element. Find index of existing element using indexOf() method. Use set(index, object) to update new element. Replace existing element in ArrayList. To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set () method to update the replace the old element with new element. Find index of existing element using indexOf () method. Use set (index, object) to update new element.

Try it:

if(chat_lists.contains(chat_list)){
  chat_lists.remove(chat_list);
  chat_lists.add(chat_list);
} else {
  chat_lists.add(chat_list);
}

ArrayList replace element if exists at a given index?, For example, if you want to replace the first element then you need to call set(0, Now, the questions come why do you want to replace an element in the ArrayList​? Here is an example of replacing an existing value from ArrayList in Java. You should read a comprehensive book like "Big Java Early Object" by Cay S. This method replaces old value with new value . To replace ArrayList contents with new value : Method signature: Object set(int index, Object newObj); This method is used to replace/update content of ArrayList element i.e.; replacing old value with new value; returns old object value; ReplaceArrayListContentWithNewValue.java

Read about architecture patterns, for example, MVP. You need to store your messages somethere (in Model) and update view relative to data.

Also read about RecyclerView, cause of ListView is a little bit deprecated

How to replace existing element in ArrayList, For example, the following code snippet will create two elements in ArrayList: The second line finds out that Mary already exists, doesn't change it, and returns false: A map can't contain duplicate keys, and each key can be mapped to only one value (object). You see You can restrict the size of the queue if need be. ArrayList replaceAll() retains only the elements in this list that are contained in the specified method argument collection. Rest all elements are removed from the list. This method is exact opposite to removeAll() method. 1. ArrayList replaceAll() method. The replaceAll() method takes single argument of type UnaryOperator. The UnaryOperator interface is a functional interface that has a single abstract method named apply that returns a result of the same object type as the operand.

if (chat_lists.get(i).getContactname().equals(sendername)){

above statement has problem them. It's not getting under your if condition and following the chat_lists.add(chat_list) statement.

Instead equals use ignoreCasequals. If still wont it solve your problem please use debug mode or logs check chat_lists.get(i).getContactname() and sendername same or not.

How to replace an element of ArrayList in Java?, HashSet.add() method in Java HashSet is used to add a specific element into a HashSet. present in the HashSet else the function will return False if the element is already present in the HashSet. Syntax: Hash_Set.add(Object element​) Return Value: The function returns True if the element is not present in the HashSet  To replace an element at the specified index of ArrayList use Object set (int index, Object obj) method. This method replaces the specified element at the specified index in the ArrayList and returns the element previously at the specified position.

Java Programming: 24-Hour Trainer, in a String · Sum of all Palindrome Numbers present in a Linked list · How to pad a String in Java ArrayList class is used to replace the element at the specified position in this list with the specified element. if the index is not within the size range of the ArrayList. for Integer value Creating object of ArrayList<​Integer>. 3. ArrayList indexOf() example to check if element exists. As noted above, contains() method uses indexOf() method to determine if a specified element is present in the list or not. So we can also directly use the indexOf() method to check the existance of any supplied element value.

HashSet add() Method in Java, ArrayList , which is usually the better-performing implementation, and LinkedList which If you're not familiar with them from Collection , now would be a good time to read The Two List objects are equal if they contain the same elements in the same order. Here's a little method to swap two indexed values in a List . The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.

ArrayList set() method in Java with Examples, If there is a need to update the list element based on the index then set method of ArrayList class can be used. The method set(int index, Element E) 3. Compare and get missing elements from another ArrayList. Instead of retaining all the elements contained in other ArrayList from the first ArrayList object, we are going to remove all the elements contained in other ArrayList. That will give us all the elements which are not present in other ArrayList as given below.

Comments
  • so whats the problem your facing now ?
  • I'm getting 2 copies of the same item.
  • first copy didnt get replaced and second copy present at the last right ?
  • Yes that's right.