The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:
The array will be empty if the directory is empty or if no names were accepted by the filter.
How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.
String[] str = new String[0];?
String[] str = {};
But
return {};
won't work as the type information is missing.
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
Make a function which will not return null instead return an empty array you can go through below code to understand.
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
You can use following things-
1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>
Both are same.
Related
I want to pass two arrays of Strings into one string varsargs.
ie.
public void doSomething(String... ){
}
public void test(){
String[] arrayOne = ...
String[] arrayTwo = ...
doSomething(arrayOne, arrayTwo); //Doesn't work but just for an example
}
Is the best way to just concat the two arrays or is there a better way of doing this?
Sadly not possible in java as there is no spread operator (like in Kotlin, Ecmascript 6). You have to work your way around this by creating an intermediate array:
String[] arrayThree = new String[arrayOne.length + arrayTwo.length];
System.arraycopy(arrayOne, 0, arrayThree, 0, arrayOne.length);
System.arraycopy(arrayTwo, 0, arrayThree, arrayOne.length, arrayTwo.length);
doSomething(arrayThree);
Or using Streams:
String[] arrayThree = Stream.concat(Arrays.stream(arrayOne), Arrays.stream(arrayTwo))
.toArray(String[]::new);
doSomething(arrayThree);
As said, this is possible in kotlin and can be done like this:
val arrayOne: Array<String> = ...
val arrayTwo: Array<String> = ...
doSomething(*arrayOne, *arrayTwo)
or even in javascript:
const arrayOne = ...
const arrayTwo = ...
doSomething([...arrayOne, ...arrayTwo]);
This is because a vararg has to be the last parameter in a function. Here is an extract from Oracle documentation:
https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position
String... is replaced by String[], so you can't pass two array in one function expecting a vararg.
You would have to merge your arrays into one.
You can only pass multiple array in the varargs if they all are of same type
public static void doSomething(String[] ...args){
}
public static void test(){
String[] arrayOne = {};
String[] arrayTwo = {};
doSomething(arrayOne, arrayTwo); //Doesn't work but just for an example
}
You can merge two arrays with this instruction:
import org.apache.commons.lang3;
// ...
String[] both = (String[])ArrayUtils.addAll(arrayOne , arrayTwo);
doSomething(both);
// ...
or you can pass both arrays.
public void doSomething(String[] pArrayOne, String[] pArrayTwo ){
}
public void test(){
String[] arrayOne = ...
String[] arrayTwo = ...
doSomething(arrayOne, arrayTwo);
}
I have a file name and a list of extensions. I want to check if the file name ends with any of the extensions in the list I have.
String fileName = "abc.txt";
String[] extensions = {".txt", ".doc", ".pdf"};
I can manually go over the list of extensions and check if the file ends with any of the extensions in my list.
public static boolean checkIfFileHasExtension(String s, String[] extn) {
for (String entry : extn) {
if (s.endsWith(entry)) {
return true;
}
}
return false;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
String fileName = "abc.txt";
String[] extensions = {".txt", ".doc", ".pdf"};
System.out.println(checkIfFileHasExtension(fileName, extensions));
}
Is there a better way of doing it using StringUtils or Streams or any other Java libraries? I am looking for a one-liner. Thanks!
Try this.
public static boolean checkIfFileHasExtension(String s, String[] extn) {
return Arrays.stream(extn).anyMatch(entry -> s.endsWith(entry));
}
If you use a List rather than a array, you could use the contains(String) method.
Besides, you could retrieve the extension by using the
lastIndexOf() method of String combined with the subString() method.
List<String> extensions = Arrays.asList(".txt", ".doc", ".pdf");
boolean isContained = extensions.contains(fileName.subString(fileName.lastIndexOf(".")+1));
Apache Commons Lang StringUtils.endsWithAny do exactly the same as your method. You can use it like:
public static void main (String[] args) {
String fileName = "abc.txt";
String[] extensions = {".txt", ".doc", ".pdf"};
System.out.println(org.apache.commons.lang3.StringUtils.endsWithAny(fileName, extensions));
}
But as was mentioned before it's performance linear to extensions so if you have a lot of them then try to extract the extension from the file name and make a lookup against a HashSet:
String fileName = "abc.txt";
String[] extensions = {"txt", "doc", "pdf"};
HashSet<String> extensionsSet = new HashSet<>(Arrays.asList(extensions));
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
System.out.println(extensionsSet.contains(fileExt));
Note: the HashSet uses much more memory and thus it can work slowly than linear search by array. If you use at as constant it's ok but if dynamically then measure your performance.
Also if you can use the prefixes as string you can try to use precompiled regexp: it may work even faster.
A different approach is to tokenize using . as a delimiter
String fileName = "abc.txt";
List<String> extensions = Arrays.asList("txt", "doc", "pdf");
boolean checkExt(String fileName, List<String> extensions)
{
String s = fileName.split(".");
return extensions.contains(s[s.length-1]);
}
You can use StringUtils.indexOfAny
Update
From the javadoc -
public static int indexOfAny(CharSequence str,
CharSequence... searchStrs)
Find the first index of any of a set of potential substrings.
A null CharSequence will return -1. A null or zero length search array will return -1. A null search array entry will be ignored, but a search array containing "" will return 0 if str is not null. This method uses String.indexOf(String) if possible.
StringUtils.indexOfAny(null, *) = -1
StringUtils.indexOfAny(*, null) = -1
StringUtils.indexOfAny(*, []) = -1
StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
StringUtils.indexOfAny("", [""]) = 0
StringUtils.indexOfAny("", ["a"]) = -1
If I have two class constants:
List<String> workingList= new ArrayList<String>();
StringBuilder holder = new StringBuilder(50);
both residing within, call it class StringParser and primary method readStuff()...
public class StringParser{
public void readStuff(){
//parsing logic and adding <String> elements to
//said workingList...
}//end of method readStuff
followed by a method where I inspect the contents of workingList...
public String someReaderMethod()
{
int ind = 0;
for(int i = 0; i < workingList.size();i++)
{
if(workingList.get(i).contains(someExp))
{
workingList.remove(ind);
holder.append(workingList.get(i).toString());
}
else
{
++ind;
}
}
return holder.toString();
}
...given that StringBuilder holder now contains what workingList has removed, is there a way I can 'pass' the contents of StringBuilder to a new ArrayList?
Is there a reason why you want to use a StringBuilder? You can directly insert the values into a new ArrayList. I think you could do it in a simpler way.
List<String> discardedList = new ArrayList<String>();
public void readStuff() {}
public static List<String> someReaderMethod()
{
for(int i = 0; i < workingList.size(); i++)
{
if(workingList.get(i).contains(someExp))
{
discardedList.add(workingList.get(i));
workingList.remove(i);
}
}
return discardedList;
}
You will need a deliminator to parse string and then you can use Split method and convert String[] to ArrayList.
holder.append(tempList.get(i));
holder.append(";");//Deliminator
Now when you have to use it you need to do
String[] strings =holderString.split(";");
List<String> list = Arrays.asList(strings);
While appending your List elements to your StringBuilder object, you need to append an extra delimiter after every append..
Later on, you can split the String in StringBuilder on that delimiter, and then convert your String array thus obtained to an ArrayList..
I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}
Error
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
Code
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}
You need to initialize errorSoon, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.
If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.
As a side note, you could also initialize the String array inside braces, { } as so,
String[] errorSoon = {"Hello", "World"};
which is equivalent to
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
In Java 8 we can also make use of streams e.g.
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
In case we already have a list of strings (stringList) then we can collect into string array as:
String[] strings = stringList.stream().toArray(String[]::new);
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
String[] arr = {"foo", "bar"};
If you pass a string array to a method, do:
myFunc(arr);
or do:
myFunc(new String[] {"foo", "bar"});
String[] errorSoon = new String[n];
With n being how many strings it needs to hold.
You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
You can use below code to initialize size and set empty value to array of Strings
String[] row = new String[size];
Arrays.fill(row, "");
String Declaration:
String str;
String Initialization
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
String[] string=new String[60];
System.out.println(string.length);
it is initialization and getting the STRING LENGTH code in very simple way for beginners