How to remove null value from String array in java?
String[] firstArray = {"test1","","test2","test4",""};
I need the "firstArray" without null ( empty) values like this
String[] firstArray = {"test1","test2","test4"};
If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:
import java.util.ArrayList;
import java.util.List;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
List<String> list = new ArrayList<String>();
for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
firstArray = list.toArray(new String[list.size()]);
}
}
Added null to show the difference between an empty String instance ("") and null.
Since this answer is around 4.5 years old, I'm adding a Java 8 example:
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};
firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);
}
}
It seems no one has mentioned about using nonNull method which also can be used with streams in Java 8 to remove null (but not empty) as:
String[] origArray = {"Apple", "", "Cat", "Dog", "", null};
String[] cleanedArray = Arrays.stream(firstArray).filter(Objects::nonNull).toArray(String[]::new);
System.out.println(Arrays.toString(origArray));
System.out.println(Arrays.toString(cleanedArray));
And the output is:
[Apple, , Cat, Dog, , null]
[Apple, , Cat, Dog, ]
If we want to incorporate empty also then we can define a utility method (in class Utils(say)):
public static boolean isEmpty(String string) {
return (string != null && string.isEmpty());
}
And then use it to filter the items as:
Arrays.stream(firstArray).filter(Utils::isEmpty).toArray(String[]::new);
I believe Apache common also provides a utility method StringUtils.isNotEmpty which can also be used.
If you actually want to add/remove items from an array, may I suggest a List instead?
String[] firstArray = {"test1","","test2","test4",""};
ArrayList<String> list = new ArrayList<String>();
for (String s : firstArray)
if (!s.equals(""))
list.add(s);
Then, if you really need to put that back into an array:
firstArray = list.toArray(new String[list.size()]);
Using Google's guava library
String[] firstArray = {"test1","","test2","test4","",null};
Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
#Override
public boolean apply(String arg0) {
if(arg0==null) //avoid null strings
return false;
if(arg0.length()==0) //avoid empty strings
return false;
return true; // else true
}
});
This is the code that I use to remove null values from an array which does not use array lists.
String[] array = {"abc", "def", null, "g", null}; // Your array
String[] refinedArray = new String[array.length]; // A temporary placeholder array
int count = -1;
for(String s : array) {
if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
refinedArray[++count] = s; // Increments count and sets a value in the refined array
}
}
// Returns an array with the same data but refits it to a new length
array = Arrays.copyOf(refinedArray, count + 1);
Quite similar approve as already posted above. However it's easier to read.
/**
* Remove all empty spaces from array a string array
* #param arr array
* #return array without ""
*/
public static String[] removeAllEmpty(String[] arr) {
if (arr == null)
return arr;
String[] result = new String[arr.length];
int amountOfValidStrings = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].equals(""))
result[amountOfValidStrings++] = arr[i];
}
result = Arrays.copyOf(result, amountOfValidStrings);
return result;
}
A gc-friendly piece of code:
public static<X> X[] arrayOfNotNull(X[] array) {
for (int p=0, N=array.length; p<N; ++p) {
if (array[p] == null) {
int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
X[] res = Arrays.copyOf(array, m);
for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
return res;
}
}
return array;
}
It returns the original array if it contains no nulls. It does not modify the original array.
Those are zero-length strings, not null. But if you want to remove them:
firstArray[0] refers to the first element
firstArray[1] refers to the second element
You can move the second into the first thusly:
firstArray[0] = firstArray[1]
If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?
Related
I have an array like this (source)
[Maria Carolina, Luisa Joana, Lara Silva, Catarina Patricio, Paula Castro, fim, null, null, null]
and I want an array like that (destination)
[Maria Carolina, Luisa Joana, Lara Silva, Catarina Patricio, Paula Castro]
In the following code i is the number of names.
My code is:
String[] nomeCompleto = new String[10];
String[] nomes = new String[10-i];
if(i < 10) {
nomes[i] = nomeCompleto[i];
}
System.out.println(Arrays.toString(nomes));
return;
What am I doing wrong?
Edit: The question presents a source code fragment based on array indices, hence my original answer:
Use the Arrays class to do this for you.
String[] names = new String[] {"Maria Carolina", "Luisa Joana", "Lara Silva", "Catarina Patricio", "Paula Castro", "fim", null, null, null};
String[] truncated = java.util.Arrays.copyOf(names, names.length-4); // remove the last 4 names
System.out.println(java.util.Arrays.toString(truncated));
Try it online here.
Edit: Since people (not the OP) weren't too happy with that, I added: Or, to match only names of the form Firstname Lastname, use a regex:
String[] input = new String[] {"Maria Carolina", "Luisa Joana", "Lara Silva", "Catarina Patricio", "Paula Castro", "fim", null, null, null};
List<String> namesList = new ArrayList<>();
for(String name : input) {
if(name != null && name.matches("^[A-Z][A-z]+ [A-Z][a-z]+$"))
namesList.add(name);
}
String[] namesArray = namesList.toArray(new String[0]);
System.out.println(Arrays.toString(namesArray));
Try it online here.
Edit: Finally, since Dukeling commented on fim meaning end in Portuguese, a better solution might be:
Use a loop to find the first occurrence of fim and then truncate the array accordingly (as in the first code snippet in my answer).
String[] names = new String[] {"Maria Carolina", "Luisa Joana", "Lara Silva", "Catarina Patricio", "Paula Castro", "fim", null, null, null};
int newLength = names.length;
for(int i = 0; i < names.length; i++) {
if("fim".equals(names[i])) {
newLength = i;
break;
}
}
String[] truncated = java.util.Arrays.copyOf(names, newLength);
System.out.println(java.util.Arrays.toString(truncated));
Try it online here.
As per the Question's understanding Problem statement is as follows
Given a master array of String we need to return another array which contains the elements of master with null elements and element with value "fim" removed.
There can be null elements in between and not neccessary in the last and same for the element "fim"
Basic Algorithm
iterate master array
count the number of null & fim elements, create copy array of size =
master array size - null elements count
Check if the element is null if not null then add to copy array
public String[] removeNullNFimElementsFromArray(String[] master) {
int nullNFimCount = 0;
int masterSize = master.length;
for(int i = 0; i < masterSize; i++) {
if(master[i] == null || "fim".equals(master[i])) {
nullNFimCount++;
}
}
int copySize = masterSize - nullNFimCount;
String[] copyArray = new String[copySize];
for(int i = 0, j = 0; i < masterSize; i++) {
if(master[i] != null && !"fim".equals(master[i])) {
copyArray[j] = master[i];
j++;
}
}
return copyArray;
}
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
}
I have 2 string arrays.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
I'd like the result of my merge() method to concatenate each element from the first array with the respective element of the second array separated by a comma.
Below is my code
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
This does not work. What's wrong with my code?
What's wrong is that you are looping over expectationsList and breaking out of the loop after the first iteration:
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
So the result is that you are always retrieving the first element of expectationsList.
Since what you want is to loop over two arrays, you should use an index:
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
Also, note that this implies that the size of testList is the same as the size of expectationsList. Your method should probably throw an exception if this is not the case.
Note that you do not need to convert the input arrays into lists. You can use them as-is.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 solution:
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
You're iterating through each member of testList and then for each one, iterating through each member of expectationsList. You want to iterate through each of both of them together.
What you want to do is something like this:
private static String[] merge(String[] tests, String[] expectations) {
String[] result = new String[tests.length];
for(int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i];
}
return result;
}
This code makes the assumption that tests and expectations have the same length. You might want to do a check for that at the beginning:
if (tests.length != expectations.length) {
throw new IllegalArgumentException("tests and expectations are of different lengths")
}
Notice how now you're getting the element at the same index from both arrays.
Sidenote: You can iterate over arrays with the for each format. This works just fine:
String[] myStringArray = getStringArray();
for (String myString : myStringArray) {
// Do something
}
You don't need to convert to a List in order to iterate :)
Below are the 2 ways to remove null values, which one is the best approach?
public static String[] clean(final String[] v) {
List<String> list = new ArrayList<String>(Arrays.asList(v));
list.removeAll(Collections.singleton(null));
return list.toArray(new String[list.size()]);
}
public static String[] clean(final String[] v) {
List<String> list = new ArrayList<String>(v.length);
for (String aString : v)
{
if (aString != null)
{
list.add(aString);
}
}
return list.toArray(new String[list.size()]);
}
For removing null values from a single string, I would use a regular expression like this,
private static Pattern pattern = Pattern.compile("(?i)[(\\[{]?null[)\\]}]?");
public static String removeNullString(String value) {
if (StringUtils.isEmpty(value)) {
return StringUtils.EMPTY;
}
Matcher matcher = pattern.matcher(value);
return matcher.replaceAll(StringUtils.EMPTY);
}
It covers up all "null" and empty character from string.
For removing null value from a string array in Java 7,
String[] firstArray = {"test1", "", "test2", "test4", "", null};
List<String> list = new ArrayList<String>();
for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}
firstArray = list.toArray(new String[list.size()]);
For removing null value from a string array in Java 8,
String[] firstArray = {"test1", "", "test2", "test4", "", null};
firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);
Performance wise, it is usually better to minimize calls outside of the scope of the current code block (ie method). Also, since memory allocation is relatively slow compared most other instructions, avoiding object creation is typically a goal. The best I can come up with in terms of performance (I chose to make it flexible enough to take any type of array):
public <T> T[] removeNulls(Class<T> type, final T[] original){
// first, shift all non-null instances to the head, all nulls to the end.
int nonNullCount=0;
T tempT = null;
for(int i=0; i < original.length; i++){
if(original[i] != null){
nonNullCount++;
}else if(i != original.length - 1){
// Swap the next non-null value with this null value
int j = i + 1;
// In case there are multiple null values in a row
// scan ahead until we find the next non-null value
while(j < original.length && (tempT = original[j]) == null){
j++;
}
original[nonNullCount] = tempT;
if(tempT != null){
nonNullCount++;
}
if(j < original.length){
original[j] = null;
}
i = j - 1;
}
}
// The case where there are no nulls in the array
if(nonNullCount == original.length){
return original;
}
final T[] noNulls = (T[]) Array.newInstance(type,nonNullCount);
System.arraycopy(original,0,noNulls,0,nonNullCount);
return noNulls;
}
But I'm not sure why you would want this complexity over the 3 or 4 lines to do the same thing when performance is not likely to be an issue. You would need to have HUGE arrays to see any benefit (if any) between my code and your clean example.
in Java 8 you should be able to do something like:
List<String> list = new ArrayList<String>(Arrays.asList(v));
list.removeIf(Objects::isNull);
return list.toArray(new String[list.size()]);
if you want to do it in same space i will suggest the follwing solution. But final array will also be having same size. I mean it will not shrink in size but all elements will get aggregated in same order.
public static void removeNullFromArray(String[] args) {
int location = 0;
for(int i=0; i<args.length; i++){
String arg = args[i];
if(arg!=null){
if(location<i){
args[location] = arg;
args[i] = null;
}
location++;
}
}
}
Java 8 code using streams and lambda. Filters non-nulls from an array and converts to a list.
Arrays.stream(arr).filter(Objects::nonNull).collect(Collectors.toList());
I have an ArrayList containing strings retrieved from a database. The strings are tags for individual posts of a blog, for example:
video, java, php, xml,
css, java, foo, bar,
xml, php, foo, bar, dog
I am attempting to loop through the list. Split each string by their commas into an array and check if my uniqueTag array doesn't contain an element from the split array. If it doesn't, add it to the uniqueTag array.
This is how far I've got:
List<String> tagList = conn.getAllTags();
String[] uniqueTags;
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for(int i=-1; i<=splitItem.length; i++){
// compare this element with elements in uniqueTags
// and if it doesn't exit in uniqueTags
// add it.
}
}
How do I compare and dynamically build the uniqueTags array?
I would use a Set<String> to prevent duplicate values.
Something along the lines of:
Set<String> uniques = new HashSet<String>();
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for (String item: splitItem) {
uniques.add(item.trim()); // trimming whitespace and adding to set
...
Why do not you try something like this.
Create a List<String> splitIteams of split items and do
List<String> distinct = splitItems.stream().distinct().collect(Collectors.toList());
System.out.printf("Split Items : %s, Distinct list : %s ", splitItems, distinct);
Edit - deleted one extra %s
public static void compareArrays(int[] array1, int[] array2) {
boolean b = true;
if (array1 != null && array2 != null){
if (array1.length != array2.length)
b = false;
else
for (int i = 0; i < array2.length; i++) {
if (array2[i] != array1[i]) {
b = false;
}
}
}else{
b = false;
}
System.out.println(b);
}