Java: Remove an item from existing String Array - java

I've scoured a couple of the SOF threads but can't seem to find the answer I'm looking for. Most of them provide an answer with code that's beyond the scope of what I have learned thus far.
I've tried quite a few different things and can't get this to work the way I need it to.
The program is supposed to take the given array, read it, find the given toRemove item, and re-print the array without the toRemove item.
I believe my issue is within the removeFromArray method
public static void main(String[] args)
{
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] result = removeFromArray(test, "the");
System.out.println(Arrays.toString(result));
}
public static String[] removeFromArray(String[] arr, String toRemove)
{
int newLength = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength++;
}
}
String[] result = new String[arr.length-newLength];
for(int i = 0; i < (result.length); i++)
{
if(arr[i].contains(toRemove))
{
}
else
{
result[i] = arr[i];
}
}
return result;
}
This is an assignment in my java class and we have not learned Lists (one of the answers I stumbled upon in my googling) yet so that is not an option for me.
As it is now, it should be outputting:
[this, is, example, of, call]
Currently it is outputting: [this, is, null, example, of]
Any and all help will be much appreciated!

You need 2 indices in the second loop, since you are iterating over two arrays (the input array and the output array) having different lengths.
Besides, newLength is a confusing name, since it doesn't contain the new length. It contains the difference between the input array length and the output array length. You can change its value to match its name.
int newLength = arr.length;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength--;
}
}
String[] result = new String[newLength];
int count = 0; // count tracks the current index of the output array
for(int i = 0; i < arr.length; i++) // i tracks the current index of the input array
{
if(!arr[i].contains(toRemove)) {
result[count] = arr[i];
count++;
}
}
return result;

There's the error that #Eran pointed out in your code, which can solve your problem. But I'm going to discuss another approach.
For now, you're first iterating over the entire array to find the number of occurrences to remove, and then, you're iterating over the array to remove them. Why don't you just iterate over the array, just to remove them. (I know, your first loop is helping you to determine the size of the output array, but you don't need that if you use some List like ArrayList etc.)
List<String> resultList = new ArrayList<String>();
for(int i = 0; i < arr.length; i++)
{
if(!arr[i].contains(toRemove))
{
resultList.add(arr[i]);
}
}
And you can return the resultList, but if you really need to return an array, you can convert the resultList to an array like this:
String [] resultArray = resultList.toArray(new String[resultList.size()]);
And then return this array. See this approach live here on ideone.

Try this Java8 version
List<String> test = Arrays.asList("this", "is", "the", "example", "of", "the", "call");
test.stream()
.filter(string -> !string.equals("the"))
.collect(Collectors.toList())
.forEach(System.out::println);

You can use Java Stream instead, it will give you the expected result and also your code will be clearer and really smaller.
See the method below I wrote that solves your problem.
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr)
.filter(obj -> !obj.equals(toRemove))
.toArray(String[]::new);
}
If you're unfamiliar with java Stream, please see the doc here

The following code removes all occurrences of the provided string.
Note that I have added few lines for validate the input, because if we pass a null array to your program, it would fail. You should always validate the input in the code.
public static String[] removeFromArray(String[] arr, String toRemove) {
// It is important to validate the input
if (arr == null) {
throw new IllegalArgumentException("Invalid input ! Please try again.");
}
// Count the occurrences of toRemove string.
// Use Objects.equals in case array elements or toRemove is null.
int counter = 0;
for (int i = 0; i < arr.length; i++) {
if (Objects.equals(arr[i], toRemove)) {
counter++;
}
}
// We don't need any extra space in the new array
String[] result = new String[arr.length - counter];
int resultIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (!Objects.equals(arr[i], toRemove)) {
result[resultIndex] = arr[i];
resultIndex++;
}
}
return result;
}

Related

Array of Strings into an ArrayList of Arraylist [duplicate]

This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 6 years ago.
I would like to convert an Array of Strings into an ArrayList of ArrayList, where the inner ArrayList has a dynamic number of elements. Who can help ? Thanks in advance
String[] sentences = {"hello","how are you","i am fine","and you ?","thank you"}
//Output with number of elements = 2
["hello","how are you"]
["i am fine","and you ?"]
["thank you"]
//Output with number of elements = 3
["hello","how are you","i am fine"]
["and you ?","thank you"]
public static void main(String[] args) {
String[] sentences = {"hello", "how are you", "i am fine", "and you ?", "thank you"};
System.out.println(split(2,sentences));
System.out.println(split(3,sentences));
}
public static List<List<String>> split(int numberOfElements, String[] sentences) {
List<List<String>> lists = new ArrayList<List<String>>();
int index = 0;
for (String sentence : sentences) {
if (index % numberOfElements == 0) {
lists.add(new ArrayList<String>());
}
lists.get(index / numberOfElements).add(sentences[index]);
index++;
}
return lists;
}
Output:
[[hello, how are you], [i am fine, and you ?], [thank you]]
[[hello, how are you, i am fine], [and you ?, thank you]]
public static void main(String[] args) {
String[] sentences = { "hello", "how are you", "i am fine", "and you ?", "thank you" };
List<List<String>> convertIntoList = convertIntoList(sentences, 2);
System.out.println(convertIntoList);
convertIntoList = convertIntoList(sentences, 3);
System.out.println(convertIntoList);
}
private static List<List<String>> convertIntoList(String[] sentences, int nbElement) {
List<List<String>> listOfListTarget = new ArrayList<List<String>>();
int currentIndex = 0;
while (currentIndex < sentences.length) {
int nextIndex = currentIndex + nbElement;
if (nextIndex > sentences.length) {
nextIndex = sentences.length;
}
final String[] copyOfRange = Arrays.copyOfRange(sentences, currentIndex, nextIndex);
List<String> subList = new ArrayList<String>();
subList.addAll(Arrays.asList(copyOfRange));
listOfListTarget.add(subList);
currentIndex+=nbElement;
}
return listOfListTarget;
}
Is this is a homework?
So you have an array of strings, and you want to create a List> with that, with each inner List containing at most x number of elements.
To get x number of elements and put them in a List, you can do a simple for loop.
String[] myStringArray = { ... };
List<String> myListOfString = new ArrayList<>();
for(int i=0; i<x; i++) {
myListOfString.add(myStringArray[i]);
}
So for example if you have these values
String[] myStringArray = {"a", "b", "c", "d", "e"};
x = 2;
You'll get the following list using the above loop:
["a", "b"]
Great! But we need to get all the contents of the myStringArray! How do we do that? Then let's do the first step, we iterate through all the contents of the array. We can do that like this.
int i=0;
while(i < myStringArray.length) {
System.out.println(myStringArray[i]);
i++;
}
Which will output:
a
b
c
d
e
This doesn't solve the problem... but at least we know how to iterate the whole thing. The next step is to get x of them. Sounds simple right? So basically we need to create a list of x from the contents. Maybe we can use the logic we created a few examples back to solve the problem.
// Create list of list of string here
int i = 0;
while(i < myStringArray.length) {
// Create list of string here
for(int j=0; j<x; j++) {
// Add myStringArray[j] to list of string here
}
// Add the list of string to the list of list of string here
i++;
}
Easy right? No. This gives the following lists:
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
Why? In the first loop, we are iterating up to how many is in the array. In the second loop, we are adding element 0 and 1 to a list. Obviously it wouldn't work. The second loop needs to be aware that it should not add previously added elements, and at the same time the first loop needs to be aware of what the second loop is doing. So you might think, maybe we can use the int i to indicate where the second loop should start?
int i = 0;
while(i<myStringArray.length) {
while(i<x) {
// add myStringArray[i];
i++;
}
i++;
}
Unfortunately, using the same values as previous, this will only give the following list
["a", "b"]
Because i is iterating through the whole array. So when it goes from 0 to length, whatever the value of i is used on the second array. When it loops again, i becomes 1, so the start of the second loop is at 1.
We need a separate variable to do the counting, while still keeping in mind where we currently are in the second loop.
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x) {
// Add myStringArray[count+i] to list of string
count++;
}
// Add to list of list of string
i += count + 1; // Need to be aware of how much we have processed
}
This will do what we want, but unfortunately we can get in trouble at certain values. Say x is 10 and myStringArray is only of length 2. This will throw an exception because when it reaches the point of count+i = 3, that index doesn't exist anymore. The second loop also needs to be aware of how much is still remaining.
Finally we'll have the following code
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x && count+i < myStringArray.length) {
// Add myStringArray[count+i] to list of string
}
// Add to list of list of string
i += count; // Need to be aware of how much we have processed
}
Which will give
["a", "b"]
["c", "d"]
["e"]
Edit: Next time try to put some code that you tried something.

removing duplicated words from an array

I am trying to remove duplicated words from an array, and I keep getting null values. I'm not allowed to use java sorting methods so I have to develop my own. Here's my code:
public class Duplicate{
public static void main(String[] args){
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
removeDuplicate(test);
}
public static String[] removeDuplicate(String[] words){
boolean [] isDuplicate = new boolean[words.length];
int i,j;
String[] tmp = new String[words.length];
for (i = 0; i < words.length ; i++){
if (isDuplicate[i])
continue;
for(j = 0; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
tmp[i] = words[i];
}
}
}
for(i=0;i<words.length;i++)
System.out.println(tmp[i]);
return tmp;
}
}
I tried doing
if(words == null)
words == "";
But it doesn't work. I also want to return the tmp array with a new size.
For example, test array length = 9, after removing the duplicates,I should get a new array with a length of 7.Thank you for your help.
EDIT:
result i get:
a
b
abvc
abccc
null
bbc
ccc
abc
null
You're getting nulls because the result array contains fewer words than the input array. However, you're constructing the arrays of the same length.
You don't have to sort to solve this problem. However, if you're not allowed to use the tools provided by java.utils, then this is either a poorly contrived test question or whomever told you not to use the Java utility classes is poorly informed.
You can solve without sorting by doing (assuming Java 1.5+):
public class Duplicate {
public static void main(String[] args) {
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
String[] deduped = removeDuplicate(test);
print(deduped);
}
public static String[] removeDuplicate(String[] words) {
Set<String> wordSet = new LinkedHashSet<String>();
for (String word : words) {
wordSet.add(word);
}
return wordSet.toArray(new String[wordSet.size()]);
}
public static void print(String[] words) {
for (String word : words) {
System.out.println(word);
}
}
}
The output will be:
a
b
abvc
abccc
bbc
ccc
abc
I would go for hashset to remove duplicates, it will remove duplicates since hash function for the same string will give same value, and duplicates will be eliminated. Then you can convert it to a string.
I would recommend doing this with a different approach. If you can use an ArrayList, why not just create one of those, and add the non-duplicate values to it, like this:
ArrayList<String> uniqueArrayList = new ArrayList<String>();
for(int i = 0; i < words.length; i++){
if(!uniqueArrayList.contains(words[i])){ // If the value isn't in the list already
uniqueArrayList.add(words[i]);
}
}
Now, you have an array list of all of your values without the duplicates. If you need to, you can work on converting that back to a regular array.
EDIT
I really think you should use the above option if you can, as there is no clean or decently efficient way to do this only using arrays. However, if you must, you can do something like this:
You can use the code you have to mark values as null if they are duplicates, and also create a counter to see how many unique values you have, like this:
int uniqueCounter = 0;
for(int i = 0; i < isDuplicate.length; i++){
if(!isDuplicate[i]){
uniqueCounter++;
}
}
Then, you can create a new array of the size of unique items, and loop through the words and add non-duplicate values.
String[] uniqueArray = new String[uniqueCounter];
int uniqueIndex = 0;
int wordsIndex = 0;
while(index < uniqueArray.length){
// Check if words index is not a duplicate
if(!isDuplicate[wordsIndex]){
// Add to array
uniqueArray[uniqueIndex] = words[wordsIndex];
uniqueIndex++; // Need to move to next spot in unique.
}
// Need to move to next spot in words
wordsIndex++;
}
Again, I HIGHLY recommend against something like this. It is very poor, and pains me to write, but for the sake of example on how it could be done using an array, you can try it.
I don't have the time to write functioning code, but I would reccomend to first sort the array using Arrays.sort(stringArray) and then loop throug the array coparing one string to the previous. Strings that match the previous one are duplicates.
Note: This method is probably not the fastest one and though only should be used on small arrays or in tasks where performance does not matter.
What about this approach?
public static String[] removeDuplicate(String[] words){
// remember which word is a duplicate
boolean[] isDuplicate = new boolean[words.length];
// and count them
int countDuplicate = 0;
for (int i = 0; i < words.length ; i++){
// only check "forward" because "backwards checked" duplicates have been marked yet
for(int j = i + 1; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
countDuplicate++;
}
}
}
// collect non-duplicate strings
String[] tmp = new String[words.length - countDuplicate];
int j = 0;
for (int i = 0; i < isDuplicate.length; i++) {
if (isDuplicate[i] == false) {
tmp[j] = words[i];
j++;
}
}
// and return them
return tmp;
}

Compare the index of 2 String arrays with different values Java

I have 2 parallel arrays: the first contains State Names, the second Capitals of the states.
I'm making a quiz that randomly generates a State then asks the user to enter the Capital of the state. Once the input is received I want to call a method to check if the index of the capital entered is the same as the index of the state it goes with.
ie: stateArray[0] = "New York" and capitalArray[0] = "Albany".
Check Answer Method
public static void checkAnswer(String[]stateArray, String capitalArray, String answer)
{
int index;
for (int i = 0; i < capitalArray.length; i++){
if(capitalArray[i].equalsIgnoreCase(answer)){
index = i;
}
}
if(capitalArray[index] == stateArray[index])
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
I know the second if statement is wrong. How can I compare the two arrays using the index where the users answer was found in the capitalArray?
boolean checkAnswer(String[] stateArray, String[] capitalArray, String displayedState, String answer) {
for (int i = 0; i < stateArray.length; i++) {
if (stateArray[i].equals(displayedState) && capitalArray[i].equals(answer)) {
return true;
}
}
return false;
}
Or something. The key is you need to pass in something to represent the state you displayed.
You need to keep track of the index that holds the State displayed to the user. For example, the way your code is written now gives the user the ability to get a right answer by giving a wrong answer. Take this example as explanation:
string[] stateArray = {"New York", "California"};
string[] capitalArray = {"Albany", "Sacramento"};
If you were to show "New York" as the question and the user happens to answer "Sacramento" your code would display correct.
You also need a case in which the answer does not match any of the capitals in the array. One way of doing this to implement in your code is to initiate the index to -1.
int index = -1;
Once you finish the for loop check if index is -1 and display "Your answers is not a valid State" or something along those lines.
Maybe use a HashMap, I am not completely familiar with Java it appears to be the similar to a Dictionary in Python. Dictionary object has great performance.
Since you know what state you asked about you should know its array index as well. As you see below both arrays are declared as class variables.
... class Quiz {
private String[] states = new String[50];
private String[] capitals = new String[50];
... method to fill both arrays with the correct data
public static void checkAnswer(int question, String answer)
{
if(capitalArray[question].equalsIgnoreCase(answer)){
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
}
It's better to have checkAnswer method's return type as Boolean, but I left it your way.
An alternate implementation in Java would be to use a Map instead of two arrays.
Map<String,String> stateCapitals = new HashMap<String,String>();
stateCaptitals.put("New York", "Albany");
then you can check the map with
public voic checkAnswer(String chosenState, String chosenCapital) {
if (stateCapitals.get(chosenState).equals(chosenCapital) {
System.out.println("you are correct!");
}
}
This does not do it with 2 parallel arrays, but it is a better implementation if your real concern is the type of data you mentioned, and not the arrays themselves.
Try this function it return array:-
public static String[] numSame (String[] list1, String[] list2)
{
int same = 0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
same++;
break;
}
}
}
String [] array=new String[same];
int p=0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
array[p]= list1[i]+"";
System.out.println("array[p] => "+array[p]);
p++;
break;
}
}
}
return array;
}

Possible to find whether a String array value equals any random typed string?

Let's say I got this array:
String[][]array = new String[5][5];
array[2][2] = desperate;
Would it be possible to find whether
String s = "desperate"; - equals any array element without using a for loop, and without having to manually enter the row column combination of the array assigned the value "desperate"?
while loop instead of for loop
int i = 0;
int j = 0;
while (i < n)
{
while (j < m)
{
if (array[i][j].equals("..."))
{
///
}
j++;
}
i++;
}
Use enhanced-for loop: -
String [][] array = new String[2][2];
array[1][1] = "desperate";
array[0][1] = "despee";
array[1][0] = "despete";
array[0][0] = "dete";
for (String[] innerArr: array) {
for (String value: innerArr) {
if (value.equals("desperate")) {
System.out.println(value + " == desperate");
}
}
}
Output: - desperate == desperate
A better way that I would suggest is to use ArrayList<String> to store your items.. Then you can just call contains() method to check whether the list contains that element..
List<String> listString = new ArrayList<String>();
listString.add("desperate");
listString.add("despe");
if (listString.contains("desperate")) {
System.out.println("True");
}
Output: - True
Assuming that you can't (for any reasons) change your array to another collection type:
String[][]array = new String[5][5];
array[2][2] = "desperate";
public boolean contains(String str){
return new HashSet<String>((List<String>)Arrays.asList(array)).contains(str);
}
Better than transforming it to a List since HashSet's contains() method is O(1) and the one from List is O(n).
The only way to avoid using a loop (and it not clear why you would want to) is to use a Map which you pre-build with all the strings and indexes.

String[] length count

I am declaring a String array as:
String[] items = new String[10];
items[0] = "item1";
items[1] = "item2";
How can I find length of items in an efficient way that it contains only 2 elements. items.length returns 10.
I am running a loop already which runs to its length. I want to so something with this code without adding new code/loop to count number of not-null elements. What can I replace with items.length
for (int i = 0; i < items.length; i++) {
...
}
No. You will need to loop and see how many non-null elements there are.
Consider using e.g. an ArrayList<String> instead of a raw array.
UPDATE
To answer the new part of your question, your loop can become:
for (int i = 0; (i < items.length) && (items[i] != null); i++) {
...
}
Why not use a collection:
Vector <String> items;
items.add("item1");
items.add("item2");
int length = items.size();
It is 10 already it is just that 8 of the object are set to null so you could do following
int count = 0 ;
if(items!=null){
for(String str : items){
if(str != null){
count ++;
}
}
}
With the modified question in mind, you can absolutely do nothing. There is no attribute giving you the count of not null elements, so either you'd take another collection or you'd check each value for null.
I think may this will help u
public class T1 {
public static void main(String[] args) {
String[] items = new String[10];
items[0] = "item1";
items[1] = "item2";
System.out.println(getActualSize(items));
}
public static int getActualSize(String[] items)
{
int size=0;
for(int i=0;i<items.length;i++)
{
if(items[i]!=null)
{
size=size+1;
}
}
return size;
}
}
You need to iterate and check for null.
int count = 0;
for(int i = 0; i < items.length; i++){
if(items[i] != null){
count++;
}
}
count will give the number of occupied elements
To find a number of all non-null elements in array/collection (that are not neccesary in the beginning of array) you can use elegant guava solution: Iterables.size(Iterables.filter(items, Predicates.notNull())).

Categories

Resources