OK so here is some logic thinking... What I am trying to do is loop through strings until I hit a null/empty string.. then STOP. All while putting those strings inside a string array...
Here is a sample of the code. I know it's wrong but hopefully to give you an idea of what I am trying to achieve:
int i;
wepN = new String[100];
int wepQty = 0;
boolean anyLeft = true;
while (anyLeft == true) {
for(i = 0;i < 100;i++) {
if (data.getItems().get(i).getName() == null) {
anyLeft = false;
System.out.println(data.getItems().get(i).getName() + " -NO MOARE");
}
wepN[i] = data.getItems().get(i).getName();
wepQty++;
}
}
You can use break to exit a for loop, same as you would a switch statement:
String[] wepN = new String[100];
int wepQty = 0;
for (int i=0; i < wepN.length; i++) {
if (data.getItems().get(i).getName() == null || "".equals(data.getItems().get(i).getName())) {
System.out.println(data.getItems().get(i).getName() + " -NO MOARE");
break;
}
wepN[i] = data.getItems().get(i).getName();
wepQty++;
}
Numerous ways:
String currentName;
for(i=0;i<100;++i) {
currentName=data.getItems().get(i).getName();
if(currentName == null || currentName.length() ==0) {
break;
}
// continue with old code here
}
If you don't like explicit breaks:
String currentName;
while(anyLeft) {
currentName=data.getItems().get(i).getName();
anyLeft= currentName != null && currentName.length() > 0;
if(anyLeft) {
// continue with old code here
}
}
why you need to use while here?
how about:
for (int i = 0; i < 100 && data.getItems().get(i).getName() != null; i++ {
wepN[i] = data.getItems().get(i).getName();
wepQty++;
}
or
int i = 0;
while (data.getItems().get(i).getName() != null && i < 100) {
wepN[i] = data.getItems().get(i).getName();
wepQty++;
i++
}
Something like this is what you are after:
Collection<String> original = new LinkedList<String>();
original.add("String1");
original.add("String2");
original.add("");
original.add(null);
original.add("String 3");
Collection<String> tested = new LinkedList<String>();
for(String string: original) {
if(null != string && !string.isEmpty()) {
tested.add(string);
}
}
String[] stringArray = tested.toArray(new String[tested.size()]);
I would argue not to use array at all and just stick to the Collection type however.
If you want to stop on the first occurance of a null or empty string just do:
if(null != string && !string.isEmpty()) {
tested.add(string);
} else {
break;
}
There are a few considerations depending on whether the original was a collection.
If you had an array Data[] data,
String[] dataCopy = new String[data.length];
int i = 0;
for (Data datum: data){
if (datum==null)break;
dataCopy[i++] = datum;
}
But that is not optimal because you would be assigning more array cells than necessary if the original data had 100 cells but the 50th cell is where the empty string is found.
Using an ArrayList would let the JVM manage the expansion of cells, so that at the end of it you just convert the ArrayList to an array using toArray(). It's not a conversion really, but toArray withdraws the internally managed array from the ArrayList.
ArrayList<String> dataList = new ArrayList<String>(data.length);
for (Data datum: data){
if (datum==null)break;
dataList.add(datum);
}
String[] dataCopy = {};
dataCopy = datalist.toArray(dataCopy);
Or if the array you are processing is a member of data:
ArrayList<String> dataList = new ArrayList<String>(data.length);
for (Data datum: data.getItems()){
String name = datum.getName();
if (name==null)break;
dataList.add(name);
}
String[] dataCopy = {};
dataCopy = datalist.toArray(dataCopy);
Or if the original data structure implements Iterable. Let's say the class of items is Item.
Iterator<Item> itemit = data.getItems().iterator();
ArrayList<String> dataList = new ArrayList<String>(data.length);
while(itemit.hasNext()){
String name = itemit.next().getName;
if (name==null)break;
dataList.add(name);
}
String[] dataCopy = {};
dataCopy = datalist.toArray(dataCopy);
Related
Assume there is only one null in an array. I am trying to move it right to the end using a for loop. this is what i tried.
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
I want the output to be : a,c,d,e,null. I want to able to move the null to the end regardless of its index using a FOR loop.
This is what i tried
String asd[] = new String[creatureList.length];
for (int i = 0 ; i < creatureList.length; i++) {
if (creatureList[i] != null){
asd[i] = creatureList[i];
}
creatureList = asd;
Just search for the null element and if found, shift all elements 1 position to the left. This code works even if there are more than 1 null elements in the array.
public class Test10 {
public static void main(String[] args) {
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
for (int j=0; j<example.length; j++){
if (example[j]==null){
for (int k=j+1; k<example.length; k++){
example[k-1] = example[k];
}
example[example.length-1] = null;
break;
}
}
for (int j=0; j<example.length; j++){
System.out.println(example[j]);
}
}
}
You can just use the principle of bubble sort in here.
Try this
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
for(int i=0; i < example.length - 1; ++i) {
if(example[i] == null) {
example[i] = example[i+1];
example[i+1] = null;
}
}
for(String s : example)
System.out.print(s + " ");
If you only need to print the values that way, try this
for(String s : example)
if(s != null)
System.out.print(s + " ");
System.out.print(null + " ");
A possible solution without creating a new Array would be to move the elements.
Example, assuming that example is an Array:
boolean found = false;
for(int i = 0; i < example.length; i++) {
if(found)
example[i-1] = example[i];
if(example[i] == null)
found = true;
if(i == example.length - 1 && found)
example[i] = null;
}
I want to add that this would be a lot easier if you would use Collections (for example an ArrayList), I highly recommend using them instead of Arrays if performance is not a huge factor.
I'd have a different implementation for ArrayLists (as .remove() is handy), but here we are with a bounded array:
for(int n = 0; n < array.length; n++) {
if(null == array[n]) {
// to avoid issues with references, unsure if necessary
String s = array[n + 1];
array[n] = array[s];
array[n + 1] = null;
}
}
Here's a solution that is based on your assumption that there's only one null:
for (int i=1; i<example.length; i++) {
if (example[i-1] == null) {
example[i-1] = example[i];
example[i] = null;
}
}
I think the answers before me were not correct, so here is a code that works and puts all the nulls at the end of a array.
public static void moveNullToTheEnd( Object[] arr )
{
Object[] temp = new Object[arr.length];
int counter = 0;
int nullcounter = arr.length-1;
for(int i= 0; i < arr.length; i++) {
if(arr[i] == null){
temp[nullcounter] = null;
nullcounter--;
}
else {
temp[counter] = arr[i];
counter++;
}
}
arr = temp;
System.out.println(Arrays.toString(arr));
}
public static void main (String[] args)
{
Object [] test = new Object[] {1, 2, null, null, 4};
moveNullToTheEnd(test);
}
Suppose this:
String s0 = "01234";
String[] S1 = {"jkl","abc","xyz"};
String[] S2 = {"OPQ","ghi","STU"};
String s3 = "56789";
get_AllStrings(s3, S1, S2, s0);
The returned String[] must be:
String[] NewArray = {"56789","OPQ","ghi","STU","01234"}
I want to obtain this strings like only one array of strings...
Here my method:
public String[] get_AllStrings(String... argString) { //Only String or String[]
int TheSize = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
TheSize += OneArray.length;
} else {
TheSize += 1;
}
}
String[] NewArray = new String[TheSize];
int ThePos = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = argString[i];
System.arraycopy(OneArray, 0, NewArray, ThePos, OneArray.length);
ThePos += OneArray.length;
} else {
String[] OneArray = {argString[i]};
System.arraycopy(OneArray, 0, NewArray, ThePos, 1);
ThePos += OneArray.length;
}
}
return NewArray;
}
But, is not working...
What you want to do is to use an ArrayList instead of an array.
public static String[] getAllStrings(Object ... argString) {
ArrayList<String> list = new ArrayList<String>();
for (Object stringOrArray : argString) {
if (stringOrArray instanceof String)
list.add((String) stringOrArray);
else {
String[] strings = (String) stringOrArray;
list.addAll(Arrays.asList(strings));
}
}
return list.toArray(new String[list.size()]);
}
I changed your code a bit and got this:
public static String[] get_AllStrings(Object... argString) {
ArrayList<String> strings = new ArrayList<String>();
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
for(String str : OneArray)
strings.add(str);
} else {
strings.add((String)argString[i]);
}
}
return (String[])strings.toArray();
}
I could not get it to accept both String and String[] with your method signature, but a change to Object... did the trick. You can use an ArrayList to create the array directly instead of looping through everything twice.
unfortunately, you're running up against Java's type system here.
String and String[] are not subtypes.
so a variable, or array can only hold one or the other.
Using object, as done by #Johan Henriksson throws away any type safety assurances from the compiler, since any object can be put in the array. this is okay if you have some garuantee that you'll only ever have Strings, and you'll need to cast to string on pulling out of the collection.
I'm not sure exactly what you're trying to achieve here
So I'm not sure how to go about resolving this.
if you just want all the strings from all sources in a collection of some sort, I'd use a list
it's unclear where you're getting these strings and string arrays from however.
You can't pass a String[] into an element of a varargs String... parameter.
The only way to accept either String or String[] is a "typeless" varargs Object..., because Object is the only common type to both.
public static String[] get_AllStrings(Object... args) {
ArrayList<String> result = new ArrayList<String>();
for (Object o : args) {
if (o instanceof String) {
result.add((String)o);
} else if (o instanceof String[]) {
result.addAll(Arrays.asList((String[])o));
} else {
throw new IllegalArgumentException();
}
}
return (String[])result.toArray();
}
I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose
Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);
I've written a method to remove null-values from an array i need in a program.
The method, however, doesn't seem to work, the null values won't go away. This is my code so far.
public void removeNull(String[] a)
{
for(int i=0; i<a.length; i++)
{
if(a[i] == null)
{
fillArray(a, i);
}
}
}
public void fillArray(String[] a, int i)
{
String[] a2 = new String[a.length-1];
for(int j=0; j<a2.length; j++)
{
if(j<i)
{
a2[j]=a[j];
}
else if(j>i)
{
a2[j]=a[j+1];
}
}
a=a2;
}
Thanks in advance!
I would advocate doing it the simple way unless performance is really a problem:
public String[] removeNull(String[] a) {
ArrayList<String> removedNull = new ArrayList<String>();
for (String str : a)
if (str != null)
removedNull.add(str);
return removedNull.toArray(new String[0]);
}
Streams API version of the solution:
SomeClass[] array = new SomeClass[N];
...
array = Arrays.stream(array).filter(Objects::nonNull).toArray(SomeClass[]::new);
(I post this down to maybe get some thoughts on applicability, relative performance etc)
hi everyone first of all i want to appologize for my english im learning at this moment and this is my first post so i want to try to put my solution about the problem here it is
String[] removeNulls(String[] nullsArray) {
int countNulls = 0;
for (int i = 0; i < nullsArray.length; i++) { // count nulls in array
if (nullsArray[i] == null) {
countNulls++;
}
}
// creating new array with new length (length of first array - counted nulls)
String[] nullsRemoved = new String[nullsArray.length - countNulls];
for (int i = 0, j = 0; i < nullsArray.length; i++) {
if (nullsArray[i] != null) {
nullsRemoved[j] = nullsArray[i];
j++;
}
}
return nullsRemoved;
}
You can't change the reference to a variable in a method and expect it to be reflected in the calling method.
You'll instead have to return the new array.
public String[] removeNull(String[] a)
{
for(int i=0; i<a.length; i++)
{
if(a[i] == null)
{
a = fillArray(a, i);
}
}
return a;
}
public String[] fillArray(String[] a, int i)
{
String[] a2 = new String[a.length-1];
for(int j=0; j<a2.length; j++)
{
if(j<i)
{
a2[j]=a[j];
}
else if(j>i)
{
a2[j]=a[j+1];
}
}
return a2;
}
This way would be faster:
private static String[] removeNulls(String[] strs) {
int i = 0;
int j = strs.length - 1;
while (i <= j) {
if (strs[j] == null) {
--j;
} else if (strs[i] != null) {
++i;
} else {
strs[i] = strs[j];
strs[j] = null;
++i; --j;
}
}
return Arrays.copyOfRange(strs, 0, i);
}
I can see two errors in your code:
Your method fillArray doesn't cover the case i == j
Your assignation a = a2; doesn't have the effect you think it might have. Arguments are passed by value in Java, and your assignment does NOT change the value of a in your first method. Try returning an instance to a2 in fillArray, and assign this value to a in removeNull.
A couple of things:
Don't you wantString[] a2 = new String[a.length-1];` to be
String[] a2 = new String[a.length];
Won't making it length - 1 make it too short?
You need a case for i == j in your code. This is why the nulls aren't getting updated.
What problem are you trying to solve with the second function? It seems complicated given what I thought your problem was.
Try this (I didn't test it):
public String[] removeNull(String[] a) {
String[] tmp = new String[a.length];
int counter = 0;
for (String s : a) {
if (s != null) {
tmp[counter++] = s;
}
}
String[] ret = new String[counter];
System.arraycopy(tmp, 0, ret, 0, counter);
return ret;
}
This way you can remove nulls in one cycle, but it will not resize array:
public static void removeNull(String[] a) {
int nullCount = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == null) {
nullCount++;
} else {
a[i-nullCount] = a[i];
}
}
}
This one creates new array, but includes two cycles:
public static String[] removeNull(String[] a) {
int nullCount = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == null) nullCount++;
}
String[] b = new String[a.length-nullCount];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != null) b[j++] = a[i];
}
return b;
}
You can think on optimizing that code using System.arraycopy. I hope the code works.
When removing values in an array, the size changes so you can't keep the same array (you could push the nulls at the end).
The structure close to an array that has a auto-adjustable size is an ArrayList. One option would be :
String[] inputs;
List<String> items = new ArrayList<String>(inputs.length);
for(String input : inputs) {
if (input != null) {
items.add(input);
}
}
String[] outputs = items.toArray(new String[items.size()]);
Performance might be a bit less than working directly with arrays, but because an array has a fixed size, you would need two loops with arrays :
one to count the number of non-null values
after building the array, the same loop to copy the values.
This might not have an ideal performance either, and it is really much more complex to get it right...
Another approach would be to move the nulls at the end, then create a shorter array that wouldn't include the nulls. The idea would be :
String[] strings;
int writeIndex = 0;
int max = strings.length;
for(int readIndex = 0; readIndex < max; readIndex++) {
String read = strings[readIndex];
if (read != null) {
strings[writeIndex++] = read;
}
}
String[] outputs = new String[writeIndex];
System.arraycopy(strings, 0, ouputs, 0, writeIndex);
Well, more people said it before... but I also want to emphasize this solution:
You can use some type of Collection, like ArrayList or List and add only the not null elements. Finally you must return the new String[] formed by the Collection.
Here an example where you can check the correctness:
import java.util.ArrayList;
public class NullRemove {
public static String[] removeNull(String[] a) {
ArrayList<String> aux = new ArrayList<String>();
for (String elem : a) {
if (elem != null) {
aux.add(elem);
}
}
return (String[]) aux.toArray(new String[aux.size()]);
}
public static void main(String[] args) {
String[] init = new String[]{"aaa", null, "bbb", "ccc", null, "ddd",
"eee", "fff", null};
String[] result = NullRemove.removeNull(init);
System.out.println("Start Check result");
for (String elem : result) {
if (elem == null) System.out.println("NULL element");
}
System.out.println("End Check result");
}
}
The for with the code don't print anything cause there is any null element :)
Regards!
You have two options:
Create new array that length is same as the input, then assign to it not null values and add the substract it to the count of not null elememts .
Example in 0xJoKe answer.
If You need to work only sutch array you could create an adapter for it.
public class NullProofIterable<T> implements Iterable<T>{
private final T[] array;
public NullProofIterable(T[] array){
this.array = array;
}
#Override
public Iterator<T> iterator() {
return new NullProofIterator<T>(this.array);
}
private static class NullProofIterator<T> implements Iterator<T> {
private final T[] array;
private final int index = 0;
private NullProofIterator(T[] array) {
this.array = array;
}
#Override
public boolean hasNext() {
return this.index < this.array.length;
}
#Override
public T next() {
return this.array[this.index];
}
#Override
public void remove() {
throw new RuntimeException("Remove not allowed in this iterator");
}
}
}
Then in source code, only thing you have to do is:
for(String str : new NullProofIterable<String>(strArray)) {
//Perform action on not null string
}
The second option is very fancy usage of != null condition bu it might be helful when a method need to return some data.