How can i remove an element from array in Java - java

Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?

You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list

First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!

To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.

There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);

String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}

Related

Return the updated ArrayList<Characters> after removing the specified element at the index

I am trying to find out if there is a possibility of returning the updated ArrayList after removing the specified element at the index in a single line so that I can pass it on to the recursive function.
Below is a snippet of my code which tries to generate all valid parenthesis combinations given n pairs of "()" brackets.
My concern is in the recursive function call "findAllCombinations" where after some validations I want to remove one character at each recursive call from the arrayList courceSet. However sourceSet.remove(index) returns a character. Instead I want to pass the updated list after removing the character in one line. Is it possible ?
Note : The line below is syntactically wrong and just used for better illustration.
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .
I did go through the official documentation but did not find any help.
Any help is appreciated, and thanks for your time.
public class GenerateParenthesis {
char singleBracket;
List<String> answerSet = new ArrayList<String>();
char[] repoSet = {'(',')'};
public List<String> generateParenthesis(int n) {
String soFar = "(";
List<Character> sourceSet = new ArrayList<Character>();
for(int i = 0;i<n;i++){
sourceSet.add('(');
sourceSet.add(')');
}
findAllCombinations(sourceSet,soFar,'(');
return answerSet;
}
public void findAllCombinations(List<Character> sourceSet,String soFar,Character toRemove){
if(sourceSet.isEmpty()){
answerSet.add(soFar); // append to a answer set list containing all combinations
return;
}
for(int i = 0;i<2;i++){
singleBracket = repoSet[i];
int index = sourceSet.indexOf(singleBracket);
if(index!=-1) {
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket);
}
}
}
public static void main(String args[]){
GenerateParenthesis gp = new GenerateParenthesis();
List<String> ans = new ArrayList<String>();
ans = gp.generateParenthesis(3);
}
}
ArrayList (likely to most List implementations) is a mutable data structure: calling remove you modify the list rather than returning a new list without the removed element.
If you want the latter behavior, the quick and easy way is to do a copy of the list.
// (inside the if...)
// pass the original list to the constructor to make a copy
List<Character> sourceSetCopy = new ArrayList<>(sourceSet);
// modify the copy
sourceSetCopy.remove(index);
// use the modified copy
findAllCombinations(sourceSetCopy, soFar + singleBracket, singleBracket);

Replace strings populated in an ArrayList<String> with other values

I am currently working on a project where I need to check an arraylist for a certain string and if that condition is met, replace it with the new string.
I will only show the relevant code but basically what happened before is a long string is read in, split into groups of three, then those strings populate an array. I need to find and replace those values in the array, and then print them out. Here is the method that populates the arraylist:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> DNAsplit = new ArrayList<String>();
for (int i = 0; i < text.length(); i += 3)
{
DNAsplit.add(text.substring(i, Math.min(i + 3, text.length())));
}
return DNAsplit;
}
How would I search this arraylist for multiple strings (Here's an example aminoAcids = aminoAcids.replaceAll ("TAT", "Y");) and then print the new values out.
Any help is greatly appreciated.
In Java 8
list.replaceAll(s-> s.replace("TAT", "Y"));
There is no such "replace all" method on a list. You need to apply the replacement element-wise; the only difference vs doing this on a single string is that you need to get the value out of the list, and set the new value back into the list:
ListIterator<String> it = DNAsplit.listIterator();
while (it.hasNext()) {
// Get from the list.
String current = it.next();
// Apply the transformation.
String newValue = current.replace("TAT", "Y");
// Set back into the list.
it.set(newValue);
}
And if you want to print the new values out:
System.out.println(DNAsplit);
Why dont you create a hashmap that has a key-value and use it during the load time to populate this list instead of revising it later ?
Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");
And use it like below :
//Use the hash map to lookup the temp key
temp= text.substring(i, Math.min(i + 3, text.length()));
DNAsplit.add(dnaMap.get(temp));

How can I check if an ArrayList<String> contains any elements from an array of Strings?

Within Android, I'd like to perform an if statement to check whether an ArrayList contains any element from an array of Strings?
e.g.
Check whether any of the elements from singingGroup are also containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
How can I do this? as I know how to check if one item is contained as in another array as below. But not if any from one, exist in another.
if (Arrays.asList(Winners).contains(singingGroup)) {
You can use
Collections.disjoint(singingGroup, Arrays.asList(Winners));
to test, is the 2 arguments have no common element(s) in common. (see also javadoc)
The negation of the result seems to be what you're looking for.
Collections.disjoint is one way to archive this but You can also use retainAll() method.
Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.
Case I :elements from singingGroup are not containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
List<String> WinnerList = new ArrayList<>(Arrays.asList(Winners));
WinnerList.retainAll(singingGroup);
System.out.println("retainList = " + WinnerList);
Output
list1 = []
Case II:elements from singingGroup are also containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Steven");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Jennifer");
List<String> WinnerList = new ArrayList<>(Arrays.asList(Winners));
WinnerList.retainAll(singingGroup);
System.out.println("retainList = " + WinnerList);
Output
retainList = [Jennifer, Steven]
you can also check like this:
String Winners[] = {"Jennifer", "Patrick", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
for(int i=0; i< Winners.length;i++)
{
if(singingGroup.contains(Winners[i]))
{
System.out.println("duplicate");
}
}
You can use the CollectionUtils class provided by Apache Commons.
Using the intersection method (useful if you want to do something with the common elements):
Collection<String> intersection = CollectionUtils.intersection(singingGroup, Arrays.asList(Winners));
if (intersection.size() > 0){
// At least one element contained in the intersection
}
Or, using the containsAny method:
if (CollectionUtils.containsAny(singingGroup, Arrays.asList(Winners))){
// True if at least one common element exists in both lists
}
//for loop would be perfect to check if element i = element i
int i =0;
int loopCount = 0;
while(loopCount < Winners.lenght)
{
for(int i =0; i < singingGroup.length; i++)
{
if(Winners[loopCount] == singingGroup[i])
{
System.out.println(Winners[loopCount] + "is apart of the winners");
}//end of comparing if
if(i == singing.Group.length)
{
loopCount ++;
} //end of i == singingGroup
}//end of for loop
}//end of while loop
This is not the most optimal code but if you need it in a hurry this will work

Copying the first two values of an array into a new array

I have sorted an array of objects into descending order based on one of their variables. I now need to take the first two values of this array and place them in a new String array. What I have so far is below, but Im obviously making a stupid mistake somewhere.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teams[i] = teamsToProgress[i];
}
}
You try to assign String to a Team field (here: teams[i] = teamsToProgress[i];). You'll have to convert (not casting) the String to a Team instance before assigning.
If your just looking for a logical error, here it is:
teams[i] = teamsToProgress[i]; should be replaced to teamsToProgress[i] = teams[i];
I'm not getting into the details of the syntax involved. But I guess this is what you wanted based on your question.
teams[i] = teamsToProgress[i]; should be reversed, this make no sense. You're also missing a return statement.
public String[] teamsToProgress()
{
Arrays.sort(teams);
String[] teamsToProgress = new String[2];
for (int i=0; i<2 ; i++)
{
teamsToProgress[i] = teams[i]; //.getSomething() ?
}
return teamsToProgress;
}
your question is not clear enough as we still need to learn about Team object structure. but I'm guessing you are looking after something like this.
public String[] teamsToProgress(Team[] teams) //pass your sorted teams array as a param.
{
String[] teamsToProgress = new String[2];
for (int i=0; i<2; i++)
{
teamsToProgress[i] = String.valueOf(teams[i]); //convert teams[i] to string
}
return teamsToProgress;// you need to return an array
}

Moving indices in an array

I am trying to write a write a program that receives an String[] and prints out the array with the first string alphabetically first. I have to use three methods like these. Here is a sample input/output:
bob, joe, aaron, zack ----> aaron, bob, joe, zack
findFirstName() is correctly finding the first String alphabetically and returning its location.
MoveToRightOne is correctly shifting each String right one while overwriting the first string alphabetically and repeating the first one (ex: bob bob joe zack).
moveName() is not working correctly. It is supposed to replace the first instance of "bob" with "aaron" but is usually off by one or two places.
Does anyone see why this might be happening in moveOne()?
public static String [] moveName(String [] names) {
String names1 [] = names.clone();
int firstPosition = findFirstName(names1);
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
String firstAlph= names1 [firstPosition];
System.out.println(names1 [firstPosition]);
NewNames [0] = firstAlph;
return NewNames;
}
public static int findFirstName(String[ ] names1 ) {
// receives an array of Strings, and returns the location (i.e. index) of the first
// name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static String[] moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (startSpot - 1); i >= 0; i--) {
names[i+1] = names[i];
}
return names;
}
moveToRightOne does not make a copy of the names array that you pass in. Instead, it modifies it directly. That means when you say
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
the strings will be shifted in names1, and after that, NewNames and names1 will just be references to the same array. I think your intent is to make NewNames be an array with the strings shifted, and leave names1 alone, but that isn't what's happening. That means that the following statement is going to return the wrong string:
String firstAlph= names1 [firstPosition];
(Or, since names1 is already a clone of names, maybe what you want is to use names instead of names1 when trying to access elements from the not-yet-shifted array.)
Your moveToRightOne function was broken, so you were not actually using all the parameters passed in. Also, you should grab the first name alphabetically before you actually overwrite it using that function.
public class Shift {
public static void moveName(String [] names) {
int firstPosition = findFirstName(names);
// Store the name at that position
String firstName = names[firstPosition];
moveToRightOne(names, 0, firstPosition);
names [0] = firstName;
}
public static int findFirstName(String[] names1) {
// receives an array of Strings, and returns the location (i.e. index)
// of the first name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static void moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (endSpot - 1); i >= startSpot; i--) {
names[i+1] = names[i];
}
}
public static void main(String[] args) {
String[] original = new String[] { "bob", "joe", "aaron", "zac"};
for (String s: original) System.out.println(s);
System.out.println();
moveName(original);
for (String s: original) System.out.println(s);
}
}
Are you sure the moveToRightOne is correct? (if firstPosition is 0 you will get no changes as the for loop will not execute)
Just a quick Thought:
If you are looking do a sort manually (I assume this is for a class). I will also assume you are trying to implement insertion sort algorithm (otherwise Arrays.sort() is your friend). The way you are approaching it, it looks like you will be making multiple passes through the array to achieve a sort. if you want to do that switch to bubble sort instead.
The description of the insertion sort code will look something like this:
Start looping through your array, compare that the element at index is greater than element at index + 1. if not true move to the next element. if true compare the smaller element (call it A) to all previous elements until it is greater than the next previous element (lets call it B). Save a copy of A Shift all elements after B to the right (by 1) until you get to the A's old position . insert the copy of A into position just after B. Continue from the old A's index. Rinse/repeat until the end of the array
you may want to simplify your code in that case (and always check for edge conditions like 0 and Array.length)
HTH
Please use Arrays.sort() for sorting instead.This is not exact solution for the problem, but an alternate way for it.
import java.util.Arrays;
public class Test{
Public static void main(String args[]){
String str[]= {'Mike','Adam','Peter','Brian'};
System.out.println("str"+str[0]); // Mike
Arrays.sort(str);
System.out.println("str"+str[0]); //Adam
}
}

Categories

Resources