Jump to content

How to remove a name from string array


Recommended Posts

Hello,

I am trying to do a task. I have a list of people’s names “John”,”Mike”,”Sam”. How can I remove all the names named “Mike”? Can you please help me?

I am getting few errors in the below code:

package QA1;

import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;

public class JavaRemoveNameArray {
	String[] myStrArray = {"John","Mike","Sam"};
	
	System.out.println("Before: "+Arrays.toString(myStrArray));
	
	List<String> myList = new ArrayList<String>(Arrays.asList(myStrArray));
	myList.remove("Mike");
	
	myStrArray = myList.toArray(new String[0]);
	
	System.out.println("After: "+Arrays.toString(myStrArray));
}

Thanks!

Edited by newcoder1010
Link to post
Share on other sites
public static Object[] remove(Object[] array, Object element) {
    if (array.length > 0) {
        int index = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(element)) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            Object[] copy = (Object[]) Array.newInstance(array.getClass()
                    .getComponentType(), array.length - 1);
            if (copy.length > 0) {
                System.arraycopy(array, 0, copy, 0, index);
                System.arraycopy(array, index + 1, copy, index, copy.length - index);
            }
            return copy;
        }
    }
    return array;
}

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...