How to remove certain elements from my array in my Java code - java

I am working on the following coding prompt for my class:
Your task is to write a method with the following signature:
public static String[] removeFromArray(String[] arr, String toRemove)
The method should return a string array that has the same contents as arr, except without any
occurrences of the toRemove string. For example, if your method is called by the code below
String[] test = {“this”, “is”, “the”, “example”, “of”, “the”, “call”};
String[] result = removeFromArray(test, “the”);
System.out.println(Arrays.toString(result));
it should generate the following output:
[this, is, example, of, call]
Note: Your method will be passed values for arr and toRemove by the testing program – you should not
read these values in from the user inside your method. Also, you must write this method with the
signature requested above in order to receive credit. You do not need to write the code that calls the
method – only the method itself.
Hint: Because you must specify the length of an array when you create it, you will likely need to make
two loops through the input array: one to count the number of occurrences of the toRemove string so
that you can create the new array with the proper size and a second to copy all of the other strings to the new array.
I have everything working in my code but the last part where I have to print out the new array does not work, I know I have make it smaller so it will print out properly, but I can't get that part to work. I know I have to get rid of the null, but I don't know how. Also my code has to work for any array not just the test case I have. Some help or advice would really be nice. Thank you very much!!! :)
Here is my code:
public static void main(String[] args) {
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] remove = removeFromArray(test, "the");
System.out.println(Arrays.toString(remove));
}
public static String[] removeFromArray(String[] arr, String toRemove) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toRemove)) {
count++;
}
}
String[] result = new String[arr.length - count];
//for (int i = 0; i < arr.length; i++) {
// if(!arr[i].equals(toRemove)){
// result[].equals(arr[i]);
//}
//}
return result;
}

you approach looks ok, it looks like the commented code yor are trying to assign the new array with the wrong emthod
you should use result[i] = arr[i] ; instead of result[].equals(arr[i]);
do at the end:
String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[k] = arr[i];
k++;
}
}
return result;

Your last part should be assigning the value to the array one by one.
int j = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[j++] = arr[i];
}
}

It's asking you to return a new String array which excludes the given word. Loop through the array and add word which does not equal to the given word.
public static String[] removeFromArray(String[] arr, String toRemove){
ArrayList<String> words = new ArrayList<>();
for(String s : arr)
if(!s.equals(toRemove))
words.add(s);
return words.toArray(new String[0]);
}
Since array size cannot be changed after being created, use an ArrayList to store the words, then return as an array.

I know you're new to programming itself, so the solutions given are perfectly fine.
However, using Java, you'd usually use the libraries; in this case, the Collections library. If you're using Java 8, this is how you would do it:
public static String[] removeFromArray(String[] arr, String toRemove) {
// create a List and fill it with your items
ArrayList<String> list = new ArrayList();
Collections.addAll(list, arr);
// remove the items that are equal to the one to be removed
list.removeIf(s -> toRemove.equals(s));
// transfer back to array
return list.toArray(new String[list.size()]);
}
Then, there are Java 8 Streams, which would make this
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr) // create stream from array
.filter(s -> !toRemove.equals(s)) // filter out items
.toArray(String[]::new); // create array from stream
}

Related

How to remove from an array without using the classes Arrays, Collections, Set, or Map?

test[0] = "one";
test[1] = "two";
test[2] = "one";
test[3] = "three";
I want to remove all the occurrences of "one" but can't use the classes Arrays, Collections, Set, or Map. Thats why I'm stuck, if it wasn't for the restriction I would be able to remove them.
You could have a method like so:
public static String[] removeFromArray(String[] inputArray, String removeString) {
int removeStringOccurences = 0;
for (String currString : inputArray) {
if (currString.equals(removeString)) {
removeStringOccurences++;
}
}
String[] result = new String[inputArray.length - removeStringOccurences];
int index = 0;
for (String currString : inputArray) {
if (!currString.equals(removeString)) {
result[index] = currString;
index++;
}
}
return result;
}
This first checks to see how many times the String we want to remove occurs and then creates a new String[] based on the length of the original String[] minus the times the undesired String occurs.
Running the following:
String[] test = new String[]{"one", "two", "one", "three"};
System.out.println("Before:");
System.out.println(Arrays.toString(test));
test = removeFromArray(test, "one"); //Call our method
System.out.println("\nAfter:");
System.out.println(Arrays.toString(test));
Results in:
Before:
[one, two, one, three]
After:
[two, three]
I think the most appropriate way of solving your issue is to take all of the elements after the element, you want to remove, and shift them one to the front. But this would leave a trail of one unused element.
You could also create a new array without the element to remove.
public void removeFromArrayShift(Object[] arr,int index) {
for(int i = 0;i< arr.length -1;i++){
if(i >= index)
arr[i]=arr[i+1];
}
arr[arr.length-1]=null;
}
public Object[] removeFromArrayNew(Object[] arr, int index) {
Object[] n = new Object[arr.length - 1];
for(int i = 0; i < n.length;i++)
if(i>= index)
n[i] = arr[i+1];
else
n[i] = arr[i];
return n
}
The later could be optimized with System.arrayCopy if you can access that. ;)

Sorting Strings as inserted into array in Java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

Array list in java

I am trying to do this problem but can't get around with it. Please tell me what i did wrong and any tips on how to solving it? Thanks.
here is the problem:
Write a method stutter that takes an ArrayList of Strings and an integer k as parameters and that replaces every string with k copies of that string. For example, if the list stores the values ["how", "are", "you?"] before the method is called and k is 4, it should store the values ["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"] after the method finishes executing. If k is 0 or negative, the list should be empty after the call.
my code:
public static void stutter(ArrayList<String> list,int k) {
String s = "";
for(int i = 0; i<list.size(); i++) {
s = list.get(i);
}
for(int j = 0; j < k; j++) {
list.add(j,s);
}
}
Well...two things are wrong here:
You're not returning anything, which is a bit of a problem if you want to get back the modified list without changing/destroying your original data.
Your loops aren't doing anything meaningful. The first loop is only going to give you the last element in your list, and then you only add that k times. Most definitely not what you want.
I won't give the entire thing away, as this is an exercise for you, but here's some suggestions:
Create your own ArrayList<String> to return instead of that String variable. You'll also be declaring the method to return ArrayList<String>. May as well initialize it, too.
Read each word in the list passed in. Add that to the local list k times (hint: nested loops). If there's no words to be read, then the loop to add the elements isn't fired.
Here is the code
public static List<String> stutter(ArrayList<String> list,int k) {
List<String> resultList=new ArrayList<String>(); // creating new list
if(k<=0) {
return resultList; //return empty list. Return null if necessary
} else {
for(String s : list) { //looping the list input
for(int i=0;i<k;i++) {
resultList.add(s); // adding the same string k times
}
}
return resultList;
}
}
Second for loop should be nested in first for loop
And strings should be added to a newlist instead of adding them to
the samelist
Done modifications to your code.
public static void stutter(List<String> list,int k) {
String s = "";
List<String> newList=new ArrayList<String>();
if(k>0) {
for(int i = 0; i<list.size(); i++) {
s = list.get(i);
for(int j = 0; j < k; j++) {
newList.add(s);
}
}
}
list=newList; // Assigning it your input list since you want to change the actual list
System.out.println(list.toString()); //Since not returning anything, printing the data
}

How can I convert List<List<String>> into String[][]?

In my project I have a List that contains Lists of Strings (List<List<String>>) and now I have to convert this List into an array of String arrays (String[][]).
If I had a single List<String> (for example myList) then I could do this to convert to String[]:
String[] myArray = new String[myList.size()];
myArray = myList.toArray(myArray);
But in this case I have lots of List of String inside a List (of List of Strings).
How can I do this? I've spent lots of time but I didn't find a solution..
I wrote a generic utility method few days back for my own usage, which converts a List<List<T>> to T[][]. Here's the method. You can use it for your purpose:
public static <T> T[][] multiListToArray(final List<List<T>> listOfList,
final Class<T> classz) {
final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);
for (int i = 0; i < listOfList.size(); i++) {
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
}
return array;
}
There I've created the array using Array#newInstance() method, since you cannot create an array of type parameter T directly.
Since we're creating a 2-D array, and we don't yet know how many columns you will be having, I've given the column size as 0 initially. Anyways, the code is initializing each row with a new array inside the for loop. So, you don't need to worry about that.
This line:
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
uses the List#toArray(T[]) method to convert the inner list to an array, as you already did. I'm just passing an array as a parameter to the method so that the return value which I get is T[], which I can directly assign to the current row - array[i].
Now you can use this method as:
String[][] arr = multiListToArray(yourList, String.class);
Thanks to #arshaji, you can modify the generic method to pass the uninitialized array as 2nd parameter, instead of Class<T>:
public static <T> void multiListToArray(final List<List<T>> listOfList,
final T[][] arr) {
for (int i = 0; i < listOfList.size(); ++i) {
arr[i] = listOfList.get(i).toArray(arr[i]);
}
}
But then, you have to pass the array to this method like this:
List<List<String>> list = new ArrayList<>();
// Initialize list
String[][] arr = new String[list.size()][0];
multiListToArray(list, arr);
Note that, since now we are passing the array as argument, you no longer need to return it from your method. The modification done in the array will be reflected to the array in the calling code.
String[][] myArray = new String[myList.size()][];
for (int i = 0; i < myList.size(); i++) {
List<String> row = myList.get(i);
myArray[i] = row.toArray(new String[row.size()]);
}
Here is one way
List<List<String>> list = new ArrayList<List<String>>();
String[][] array = new String[list.size()][];
int counter1 = 0;
for(List<String> outterList : list)
{
array[counter1] = new String[outterList.size()];
int counter2 = 0;
for(String s : outterList)
{
array[counter1][counter2] = s;
counter2++;
}
counter1++;
}
To init String[][], you should init the list(array) of String[]
So you need to define a list
List<String[]> string = new List<String[]>();
for (int i = 0;....)
{
String[] _str = new String[numbers];
_str[0] = ...
string.append(_str);
}

How can I transform a List of List (multidimensional List) to an Array of Array(multidimensional Array)?

I have written this code, but at run time I have this error:
[Ljava.lang.Object; cannot be cast to [[Ljava.lang.String;
please help me, thanks!!!
public java.util.List<String> concatAll(java.util.List<java.util.List<String>> mergedList) {
java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
Iterator<java.util.List<String>> itr = mergedList.iterator();
java.util.List<String> list1 = itr.next();
java.lang.String [] firstArray = (String[])list1.toArray();
int totalLength = firstArray.length;
for (String[] array : mergedArray) {
totalLength += array.length;
}
String[] result = Arrays.copyOf(firstArray, totalLength);
int offset = firstArray.length;
for (String[] array : mergedArray) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
java.util.List<String> finalList = Arrays.asList(result);
for (String list : finalList)
System.out.println(list);
return finalList;
}
mergedList.toArray() creates a singly indexed array typed as objects.
Each of the objects it contains is in fact a (singly-indexed) list of strings, though with this call syntax the type is not known at compile-time. It is not an array of strings, as would be needed for your cast to work.
Since your concatAll is trying to convert a List<List<String>> into a List<String> by some sort of concatenation operation, it may be best to do this without ever converting to a String[][] at all, but if you do want that conversion, it can be done as follows:
private String[][] toDoubleIndexArray(List<List<String>> mergedList) {
String[][] result = new String[mergedList.size()][];
for (int i = 0; i< mergedList.size(); i++) {
List<String> currentList = mergedList.get(i);
result[i] = currentList.toArray(new String[currentList.size()]);
}
return result;
}
Original answer, not quite correct as noted by Xavi Lopez in comments:
Since mergedList has type List<List<String>>,
mergedList.toArray() has type List<String>[], i.e., it's an array of lists, and not a doubly indexed array.
There's no out-of-the-box method, but it's fairly straightforward to do by hand:
// Create the outer dimension of the array, with the same size as the total list
String[][] mergedArray = new String[mergedList.size()][];
// Now iterate over each nested list and convert them into the String[]
// instances that form the inner dimension
for (int i = 0; i < mergedList.size(); i++) {
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
A slightly more efficient version of the loop body would be
List<String> innerList = mergedList.get(i);
String[] innerAsArray = innerList.toArray(new String[innerList.size()]);
mergedArray[i] = innerAsArray;
as this avoids the array resizing that would be required in my initial example (the new String[0] isn't large enough to hold the list elements). But quite frankly, unless this was a performance critical loop, I'd prefer the first version as I find it slightly clearer to see what's going on.
Hey you cannot convert the Multi dimentional String list to String array directly. Add the below code before trying to use the mergedArray:
/** Create Array **/
String [][] mergedArray = new String[mergedList.size()][];
/** Initialize array from list **/
for(int i=0; i< mergedList.size(); i++){
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}
This should do the trick
I think your return type is wrong if your intention is to return an array of array.
Try this:
public String[][] concatAll(java.util.List<java.util.List<String>> mergedList) {
//java.lang.String [][] mergedArray = (String[][])mergedList.toArray();
java.lang.String[][] mergedArray = new String[mergedList.size()][];
Iterator<java.util.List<String>> itr = mergedList.iterator();
int count = 0;
while (itr.hasNext())
{
java.util.List<String> list1 = itr.next();
String[] array1 = list1.toArray(new String[list1.size()]);
mergedArray[count++] = array1;
}
return mergedArray;
}
You can't convert a
List<List<String>>
to a String[][] by using the out of the box toArray functionality. This would only work if you had:
List<String[]>.

Categories