Getting rid of empty elements in ArrayList - java

I've been working on this question for a while and I'm still stumped.
I'm supposed to write a method stutter that takes an ArrayList<String> as a parameter and that replaces every string with two of that string. For example, if the list stores the values {"how", "are", "you?"} before the method is called, it should store the values {"how", "how", "are", "are", "you?", "you?"} after the method finishes executing.
But despite my best efforts I still can't seem to get rid of the empty elements that are in my code.
Any help would be greatly appreciated.
public static ArrayList<String> stutter(ArrayList<String> lst) {
ArrayList<String> list = new ArrayList<String>();
int size = lst.size();
int intSize = lst.size();
int inSize = lst.size();
int size4 = list.size();
if (lst.size() == 0) {
lst.clear();
} else {
for (int x = 0; x < size; x++) {
for (int i = 0; i < 2; i++) {
lst.add(lst.get(x));
}
}
for (int x = 0; x < intSize ; x++) {
lst.set(x,"");
}
for (int x = inSize - 1; x < size; x++) {
String oldInfo = lst.get(x);
list.add(oldInfo);
}
list.removeAll("",null);
}
return list;
}

Try this approach:
public void duplicate(final List<String> inputList) {
final List<String> temp = new ArrayList<>();
inputList.forEach(element -> {
temp.add(element);
temp.add(element);
});
inputList.clear();
inputList.addAll(temp);
}
Basically what I am doing here: another list called temp is used to store each element from your initial list 2 times. After that I just clean the initial list and add new stuff.
Instead of clear and addAll you can just return temp - it contains data as you need. But don't forget to change method return type from void to List<String> in that case.
Happy Coding :)

Try this
public static ArrayList<String> stutter(ArrayList<String> lst) {
ArrayList<String> list = new ArrayList<String>();
if (!lst.isEmpty()) {
for (String string : lst) {
list.add(string);
list.add(string);
}
}
return list;
}
}
this could do what you need , its basically checks list if not empty and duplicate the strings in the list

Following up on already good answers, here is my example with keeping the original sample method signature:
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Stutter {
public static List<String> stutter(final List<String> words) {
// Create the response array.
List<String> response = new ArrayList<>();
// Check for valid arguments. If not, return empty array of words.
if (words == null || words.size() <= 0) {
return response;
}
// Iterate over the words that were passed in.
for (final String word : words) {
// Add the words twice to the response.
response.add(word);
response.add(word);
}
// The stutter response.
return response;
}
public static void main(final String[] args) {
final String[] myWords = { "hello", "world" };
final List<String> myStutterWords = stutter(new ArrayList<>(Arrays.asList(myWords)));
for (final String s : myStutterWords) {
System.out.println(s);
}
}
}

Related

How to sort an ArrayList by length of Strings in the array

I've recently begun taking a Computer Science course to understand programming more and seem to have hit a roadblock with our lab on ArrayLists. The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.
Ex:Zebra, Deer, Giraffe
Deer
Result:Giraffe, Zebra, Deer
I've looked around online and found a few examples using ArrayList comparators but our professor wants us to do it by filtering out the largest word, printing it, removing it and then continue that loop until all words are printed out.
Here is my code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = 0;
String longest = "";
String currentWord = "";
ArrayList <String> DescendArray = new ArrayList<String>();
System.out.println("What would you like to add to the list?");
String userInput = input.next();
while(!userInput.equals("d"))
{
DescendArray.add(userInput);
userInput = input.next();
}
for (int i=0; i < DescendArray.size(); i++)
{
if (DescendArray.get(i).length() > longest.length())
{
currentWord = DescendArray.get(i);
if (currentWord.length() > longest.length())
{
longest = currentWord;
length = longest.length();
}
}
for (int j=1; j < DescendArray.size() -1 ; j++)
{
if (DescendArray.get(j - 1).length() > longest.length())
{
DescendArray.remove(j - 1);
}
System.out.println(longest + " " + length);
}
}
}
}
I'm assuming my error is somewhere in the inner loop but I can't seem to get it to work no matter how many different variations I use.
This is basically what you gotta do:
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
while(!zoo.isEmpty()) {
String bigger = "";
for(String animal : zoo) {
if(animal.length() > bigger.length()) {
bigger = animal;
}
}
System.out.println(bigger);
while(zoo.contains(bigger)) {
zoo.remove(bigger);
}
}
}
}
I'm amazed at the verbosity of other solutions. A much simpler method would be to use a stream:
List<String> original = Arrays.asList("s1", "String 2", "ss3", "s");
List<String> sorted = original.stream()
.sorted((s1, s2) -> s2.length() - s1.length())
.collect(Collectors.toList());
System.out.println(sorted);
Replace "original" with your ArrayList.
Try this, it works for me.
List<String> sorted = list.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
This seems to work. If you don't want to remove repeating animals then remove distinct() method. I omitted creation of the list.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = Arrays.asList("Zebra", "Deer", "Giraffe", "Deer");
String output = zoo.stream()
.distinct()
.sorted((x, y) -> Integer.compare(y.length(), x.length()))
.collect(Collectors.joining(","));
System.out.println(output);
}
}
Under the assumption that duplicate words need not be removed at the same time, such that a duplicate word will be removed in order, and that the list need not be done in alphabetical order (one could sort the list first), and that thread safety is not important, I would avoid using the integer counters and checking the size. Instead, I would run the output loop until everything has been removed.
As an example:
public void doRemove()
{
while (! descendArray.isEmpty()) {
String longest = "";
for (String s : descendArray) {
if (s.length() > longest.length()) {
longest = s;
}
}
if (longest.length() > 0) {
if (descendArray.remove(longest)) {
System.out.println(longest + " (" + longest.length() + ")");
}
}
} // while we stil have things to process
}
When you say descending order are you referring to the length of the string or an alphabetical comparison?
Check out how the QuickSort algorithm can be used for string sorting. You can find information on QuickSort here
The problem seems to be that for each iteration in your for loop, you arrive at Giraffe as your longest word, then you're checking the rest of the list to see if it is longer than Giraffe. Instead of what you have now, I would write something like:
for (int i=0; i < DescendArray.size(); i++)
{
longest = "";
length = longest.length();
int longestIndex = 0;
for (int j=1; j < DescendArray.size() -1 ; j++)
{
currentWord = DescendArray.get(j);
if (currentWord.length() > longest.length())
{
longestIndex = j;
longest = currentWord;
length = longest.length();
}
}
DescendArray.remove(longestIndex);
System.out.println(longest + " " + length);
}
This nested for loop should find the longest word first, store the index and print and remove the entry at that index before it finds the next longest entry.
Here is another variation which can be used, but involves an extra array list:
ArrayList<String> DescendArray = new ArrayList<>();
DescendArray.add("Monkey");
DescendArray.add("Giraffe");
DescendArray.add("Hippo");
DescendArray.add("Zebra");
DescendArray.add("Monkey");
List<String> copy = new ArrayList<>(DescendArray);
for (int i=0; i<DescendArray.size(); i++) {
String longest = "";
for (int j=0; j<copy.size(); j++) {
String current = copy.get(j);
if (current.length() > longest.length()) {
longest = current;
}
}
System.out.println(longest);
while(copy.contains(longest)) {
copy.remove(longest);
}
}
When you need to remove element from the list, iterator is a better way. See below for the code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
Collections.sort(zoo,new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
Iterator<String> iterator=zoo.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
iterator.remove();
}
}
}
To sort an ArrayList based on it's each String length, you can try:
private ArrayList SortwithStrlength(ArrayList templist) {
for(int i=0;i<templist.size();i++)
{
for(int j=0;j<templist.size();j++)
{
String temp;
if(templist.get(i).toString().length()<templist.get(j).toString().length())
{
temp=templist.get(i).toString();
templist.set(i, templist.get(j).toString());
templist.set(j,temp);
}
}
}
return templist;
}

How to print the string without duplicate?

I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two

Java Mixing variable String[] with String in one only array of strings

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

compare list and array

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

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