Placing null at the end of the List [duplicate] - java

This question already has answers here:
Placing null at the end of the List
(5 answers)
Closed 8 years ago.
I have an arrayList of object like that: [object 1, object 2, null,null,..,null , object 3, null,null]
I try to move object 3 after object 2 without delete "null case", but it's doesn't work. So I would like to iterate my arrayList from right to left and check if the value is not null and then move Object 3 behind object 2. I precise that I don't know the number of "null case" between object 2 and Object 3
I try to write this:
ArrayList<Type> subList = new ArrayList<Type>();
for (int i = 0; i < array.size(); i++) {
subList = array.get(i);
for (int j = subList.size(); j >=0 ; j--) {
if(subList.get(j)!=null) {
Collections.swap(subList, j, j-1);
}
}
}
edit:
solution 1: that works for my project
for(int i=0;i<subList.size();i++)
if(subList.get(i)!=null) {
for(int j=0;j<i;j++) {
if (subList.get(j)==null) {
Collections.swap(subList,i,j);
break;
}
}
}
}
solution 2 : copy in other arraylist
doesn't work for my project, don't know why
List<String> strings = Arrays.asList(new String[]{"A", null, "B"});
List<String> result = new ArrayList<String>();
for(String string : strings) {
if(string != null)
result.add(string);
}
for (int i = 0, remaining = strings.size() - result.size(); i < remaining; i++) {
result.add(null);
}

Update 2:
To swap between object with out create any new List , Use Collections.swap() ; Something like this:
public static void main(String[] args) {
ArrayList subList = new ArrayList();
subList.add("1");
subList.add("2");
subList.add(null);
subList.add(null);
subList.add("3");
for(int i=0;i<subList.size();i++)
if(subList.get(i)!=null) {
for(int j=0;j<i;j++) {
if (subList.get(j)==null) {
Collections.swap(subList,i,j);
break;
}
}
}
}
}
Update 1:
Try this :
public static void main(String[] args) {
ArrayList subList = new ArrayList();
subList.add("1");
subList.add("2");
subList.add(null);
subList.add(null);
subList.add("3");
subList=leftShift(subList);
}
public static ArrayList leftShift(ArrayList x){
ArrayList temp=new ArrayList();
int count=0;
for(Object t:x){
if(t!=null)
temp.add(t);
else
count++;
}
for (int i=0;i<count;i++)
temp.add(null);
return temp;
}

solution from top of my head, is not brilliant, but it will allow you to keep order
int nullIndex = -1;
for (int i = 0; i < list.size(); i++) {
if (nullIndex==-1 && list.get(i) == null) {
System.out.println("nullIndex ="+i);
nullIndex = i;
} else if (nullIndex >= 0 && list.get(i) != null) {
System.out.println("swap ="+i+" "+nullIndex);
list.set(nullIndex, list.get(i));
list.set(i, null);
i = nullIndex;
nullIndex=-1;
}
}
sorry i forgot you are using arraylist, you can do this simpler
int counter=0;
while(subList.contains(null)){
subList.remove(null);
counter++;
};
while(counter>0){
subList.add(null);
counter--;
}

Related

IF condition and looping through an ArrayList

The method on the top should merge two String elements in an ArrayList that are side by side with each other. If the length of the ArrayList is Odd the last String element should be left unchanged.
But the problem is that is this way the program leaves the first String element alone, while the others are merged nicely. The output looks like this:
[1, 23, 45, 67, 89]
although it has to look like this:
[12, 34, 56, 78, 9]
How is it possible to fix the problem? Preferably without using the Iterator.
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
for (int i =0; i< list.size(); i++)
//for (int i = list.size()-1; i >=0; i--)
{
// if (i == 0)
if ((list.size() + i) % 2 == 0) {
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i+ 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
//System.out.println(list);
}
else {
continue;
}
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
System.out.println(clump(list));
}
}
Your code seems to work fine if the input list has even number of elements. For the case when you have odd number of elements in the list, remove the last element from the list and save it temporarily before running your code. Add the last element back to the output returned.
This can be one solution (may not be the best solution):
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
// BEGIN CHANGES MADE
String temp = null;
int size = list.size();
if ((size%2) != 0)
{
temp = list.remove(size-1);
}
// END CHANGES MADE
for (int i =0; i< list.size(); i++)
{
if ((list.size() + i) % 2 == 0) {
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i+ 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
//System.out.println(list);
}
else {
continue;
}
}
// BEGIN CHANGES MADE
if (temp != null)
{
list.add(temp);
}
// END CHANGES MADE
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
//list.add("0");
System.out.println(clump(list));
}
}
You don't need to check if ((list.size() + i) % 2 == 0). On every iteration you can concatenate adjacent elements.
Also, you will need to loop until i < list.size()-1 instead of i < list.size() because when you remove the 2nd last element, you are already at the last index.
So remove the if-else block if ((list.size() + i) % 2 == 0).
and replace:
for (int i =0; i< list.size(); i++)
with:
for (int i = 0; i < list.size() - 1; i++)
Here is a working version of your program:
import java.util.ArrayList;
class So {
public static ArrayList<String> clump(ArrayList<String> list) {
for (int i = 0; i < list.size() - 1; i++)
// for (int i = list.size()-1; i >=0; i--)
{
// if (i == 0)
System.out.println(list);
System.out.println("list size is " + list.size());
String newElement = list.get(i) + list.get(i + 1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
// System.out.println(list);
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
System.out.println(clump(list));
}
}
I hope it helps you out. I used your code. It was enough good idea. Some change helped on it to work fine. Try it out! :D
import java.util.ArrayList;
public class Main {
public static ArrayList<String> clump (ArrayList<String> list)
{
int halfSize = list.size()/2;
for (int i =0; i < halfSize; i++) {
System.out.println(list);
String newElement = list.get(i) + list.get(i+1);
list.remove(i);
list.remove(i);
list.add(i, newElement);
}
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
list.add("10");
list.add("11");
list.add("12");
list.add("13");
System.out.println(clump(list));
}
}
private static ArrayList<String> clump(ArrayList<String> list) {
ArrayList<String> res = new ArrayList<String>();
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
res.add(itr.next() + (itr.hasNext() ? itr.next() : ""));
}
return res;
}
ArrayList<Integer> getMinCoins = new ArrayList<Integer>(); // function to receive change in the form of coins
{
for (int i: coins){
getMinCoins.add(i);
System.out.println(getMinCoins);
}
}

To remove the duplicate words from the array and returning the unique to the same array

I was trying to remove the duplicates from the list of arrays, I was trying to use simple for loop instead of hashset..
Can anyone suggest how can I improve my program:
public class removeduplicates {
public static void main(String[] args) {
String[] words={"Others","Others","Others","Sentence"};
String output=words[0];
int count=0;
for(int i=0;i<words.length-1;i++) {
for(int j=i+1;j<words.length;j++) {
if(words[i].equals(words[j])) {
count++;
}
else {
output=output+words[j];
}
}
i=count;
}
System.out.println(output);
}
}
In this program if we give input as Others, Sentence, Others, Sentence then I am not getting the required output: I need just Others and Sentence as output...
If possible I have a condition that when I am entering words array, I need the output array with only unique values in the same array words.
String [] input={"other", "other","sentence","other"};
String current=input[0];
boolean found=false;
for(int i=0; i<input.length; i++){
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
System.out.print(" " + current);
current = input[i];
found = false;
}
}
I suggest to use collections as you can't resize an array
ArrayList<String> noDuplicateList = new ArrayList<>();
String[] words={"Others","Others","Others","Sentence"};
for(int i=0;i<words.length;i++) {
if(!noDuplicateList.contains(words[i])){
noDuplicateList.add(words[i]);
}
}
Here's a link
The simplest way to solve the duplication is declared already using HashSet, Anyway look at this code using loop:
Step 1: replace duplicate value with null
String[] words={"Others","B","Sentence","A","Others","A","Sentence"};
for(int i=0; i < words.length ;i++) {
String toBeRemoved = words[i];
for(int j=i+1 ; j < words.length; j++) {
if(words[j] != null && words[j].equals(toBeRemoved)) {
words[i] = null;
}
}
}
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [null, B, null, null, Others, A, Sentence]
Step 2: Remove the null values (there are many ways to do it) for example:
List<String> list = new ArrayList<>(Arrays.asList(words));
list.removeIf(new Predicate<String>() {
#Override
public boolean test(String t) {
return (t == null || t.length() < 0);
}
});
words = list.toArray(new String[0]);
Using lambda JDK 8:
words = Arrays.stream(words).filter(t -> (t != null && t.length() > 0)).toArray(String[]::new);
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [B, Others, A, Sentence]

How to move a null to the end of array in java using FOR loop?

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);
}

removing an element from String array in android

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);

How to remove null from an array in java

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.

Categories

Resources