Is it possible to split a string into an string array that hasn't been declared?
I want to add a string array to a list, so currently I have it set like this vars.add(new String[]{s}); where s is a string. Is there anyway to make it add s.split("|")?
Or is the only option:
String [] ns = s.split("|");
vars.add(ns);
I was playing in netbeans, where I would this make a string array, with this string "A|C|D|E":
new String(s).split("|");
Is this what you're looking for?
ArrayList<String[]> vars = new ArrayList<String[]>();
String s = "A|C|D|E";
vars.add(s.split("\\|"));
Note that if you want to add the Strings individually to the list, you must do it slightly differently.
ArrayList<String> vars = new ArrayList<String>();
String s = "A|C|D|E";
for (Sting str : s.split("\\|"))
vars.add(str);
Related
if(CoverageNames.size()>0) {
StringBuffer tmp = new StringBuffer();
for(int i =0; i<CoverageNames.size();i++) {
tmp.append(CoverageNames.get(i).getText());
tmp.append(";");
}
List<String[]> covNamesListReport= new ArrayList<>();
String[] CoverageNamesListReport={"CoverageNamesListReport",tmp.toString()};
covNamesListReport.add(CoverageNamesListReport);
String CovName= covNamesListReport.toString();
CoverageReportList("CoverageNames", CovName);
}
Coverage Report List is a method that accepts two string arguments.
I'm learning right now so any other approaches are also welcome.
When converting List<String[]> to string in line covNamesListReport.toString();, the contents of the inner arrays is NOT displayed as expected and look like [[Ljava.lang.String;#726f3b58] because the arrays' toString method is invoked.
To display the contents of the inner strings properly, nested List<String> could be used:
List<List<String>> covNamesListReport = new ArrayList<>();
List<String> CoverageNamesListReport = Arrays.asList("CoverageNamesListReport", tmp.toString());
covNamesListReport.add(CoverageNamesListReport);
String CovName = covNamesListReport.toString();
// -> [[CoverageNamesListReport, AAA;BB;CCC;]]
or Arrays.toString could be used just to convert a nested array:
List<String> covNamesListReport= new ArrayList<>();
String CoverageNamesListReport= Arrays.toString(new String[] {
"CoverageNamesListReport", tmp.toString()
});
covNamesListReport.add(CoverageNamesListReport);
String CovName= covNamesListReport.toString();
// -> [[CoverageNamesListReport, AAA;BB;CCC;]]
I am trying to read this line in Java - "abc:300:xyz:def", and I'm really unsure how to do this using arrays because in the array format it would be like this: ["abc:300:xyz:def"] . I started with
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
in my constructor, but then I don't know if I add a
list.split(":")
somewhere, because if so would that be right after I initialize the ArrayList?
Any help would be appreciated!
To join the items, use String.join
ArrayList<String> list = new ArrayList<>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
String str = String.join(":", list);
To split the items, use String.split
ArrayList<String> list = Arrays.asList(str.split(":"));
Do this:
String line = "abc:300:xyz:def";
List<String> list = Arrays.asList(line.split(":"));
Now you have a list containing the 4 strings.
If you have to read a line from console you can try something like this
Scanner scanner = new Scanner(System.in);
String yourString = scanner.next();
StringTokenizer st = new StringTokenizer(yourString , ":");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
If you are looking only the arrays not the arraylist, you can just use the split method from the string
String line = "abc:300:xyz:def";
String[] stringArray = line.split(":");
I was trying to do something like:
ArrayList<String> getMerged ( String host, String port, String filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy.split(",")); //which is invalid
return merged;
}
I want to know if we can add elements of filesToCopy.split(",") with out having the overhead of using a loop.
Also, if the above operation can be done in a string array, say String[] merged (can pass filesToCopy also as String[] if needed), it would be even better coz in the end, I'll be converting this arrayList into an array.
I'm novice in Java programming, so please don't mind if this is a silly question.
You could do this in a single array:
String[] files = filesToCopy.split(","); // filesToCopy is an ArrayList, so I'm not
// sure how this works; I'm assuming it's
// a typo. Just get the files array somehow
String[] merged = new String[2 + files.length];
merged[0] = host;
merged[1] = port;
for (int i = 2; i < merged.length; i++) {
merged[i] = files[i-2];
}
Or, without "the overhead of a loop":
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
Of course, this still uses a loop "behind the scenes," which is unavoidable.
ArrayList.addAll method requires a Collection as a parameter, so just pass the filesToCopy:
String [] getMerged ( String host, String port, ArrayList<String> filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy);
return merged.toArray(new String[merged.size());
}
PS: I just a matter of opinion, but if I can choose between arrays and Collections, I always prefer to work with Collections (List, Set). Variable size and easy insertions are things to take into account.
I am not sure about what your need is.But i am sure anyone of the below methods will surely help you..
1.Covert String With Comma To A ArrayList
Program:
import java.util.Arrays;
....
String name="java,php,c";
List<String> list=Arrays.asList(name.split(","));
System.out.println(" "+list);
OutPut:
[java, php, c]
2.Covert ArrayList To StringArray
Here we can convert the same arraylist that we got in 1st method to string array.
Program:
String []names=list.toArray(new String[list.size()]);
for(String s:names){
System.out.println(""+s);
}
OutPut:
java
php
c
3.Covert ArrayList To Comma Seperated String
Here we can convert the same arraylist that we got in 1st method to string array.
For this you need To add commons-lang3-3.2.1.jar into your classpath or project libarary.
You can Download The commons-lang3-3.2.1.jar (HERE)
Program:
import org.apache.commons.lang3.StringUtils;
.....
String name=StringUtils.join(list, ",");
System.out.println("name="+name);
OutPut:
name=java,php,c
4.Updated Program
This might me the method that you needed
public String[] getMerged(String host, String port, String filesToCopy) {
String files[] = filesToCopy.split(",");
String[] merged = new String[(2 + files.length)];
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
return merged;
}
Check out these methods and notify me if your need is something other than these methods..
I converted the ArrayList<String> list which contains "String1", "String2" to String by using list.toString(). The resulted string format is [String1, String2]. Is there any way to convert this result back to ArrayList<String>?
Try applying the following code
String value = "[String1,String2,String3]";
value = value.subString(1,value.length()-1);
String[] split = value.split(",");
List<String> sampleList = Arrays.asList(split);
create a new Class extending Array List
public class CustomArrayList<Item> extends ArrayList<Item> {
and override
toString
method, which could give a comma separated String representation.
Now use
new CustomArrayList<Item>(Arrays.asList(list.toString().split(",")))
to get it back in ArrayList.
No direct way. Just get that String remove those [] from String and then split by , then add back to list.
Something like this,considering the given format.
String s = "[String1, String2]";
s = s.substring(1, s.length() - 1);
List<String> list = new ArrayList<>();
for (String string : s.split(",")) {
list.add(string.trim());
}
In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:
String s = "a,b,c,d,e,.........";
Try something like
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Arrays.asList documentation
String.split documentation
ArrayList(Collection) constructor documentation
Demo:
String s = "lorem,ipsum,dolor,sit,amet";
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]
This post has been rewritten as an article here.
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
In Java 9, using List#of, which is an Immutable List Static Factory Methods, become more simpler.
String s = "a,b,c,d,e,.........";
List<String> lst = List.of(s.split(","));
Option1:
List<String> list = Arrays.asList("hello");
Option2:
List<String> list = new ArrayList<String>(Arrays.asList("hello"));
In my opinion, Option1 is better because
we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.
its performance is much better (but it returns a fixed-size list).
Please refer to the documentation here
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
You could use:
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
If you want to convert a string into a ArrayList try this:
public ArrayList<Character> convertStringToArraylist(String str) {
ArrayList<Character> charList = new ArrayList<Character>();
for(int i = 0; i<str.length();i++){
charList.add(str.charAt(i));
}
return charList;
}
But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:
public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
ArrayList<String> stringList = new ArrayList<String>();
for (String s : strArr) {
stringList.add(s);
}
return stringList;
}
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));