Converting String to ArrayList<String> in Java - java

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

Related

How to convert this String array to array so that I can print all the results coming from a for loop to a string separated by commas

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

Which Algorithm should i use here? Finding Strings in a String Array

I have 2 Arrays.
One Array has Strings, which i look for.
static String[] namesToLookFor = { "NR", "STAFFELNR", "VONDATUM"};
the otherArray has Strings, which i got from a *.csv file.
indexString = indexReader.readLine();
indexArray = indexString.split(";");
My Goal is to system.out.println() the Values which are the indexArray[] and NOT in the namesToLookFor[].
For example:
namesToLookFor = {"NR"};
indexArray = {"HELLO","NR"};
//Any Algorithm here...
So in this case"HELLO" should be printed out, since it is NOT in the namesToLookFor[] Array.
If you are using java8 you can do the following
List<String> list = Arrays.asList(namesToLookFor);
Arrays.stream(indexArray)
.filter(item -> !list.contains(item))
.forEach(System.out::println);
You could iterate over your indexArray and check for each element if its contained in your namesToLookFor Array:
String[] namesToLookFor = {"NR"};
String[] indexArray = {"HELLO","NR"};
List<String> excludedNames = Arrays.asList(namesToLookFor);
for(String s : indexArray) {
if (!excludedNames.contains(s)) {
System.out.println(s);
}
}
Will output only "HELLO".
// Put array into set for better performance
Set<String> namesToFilter = new HashSet<>(Arrays.asList("NR", "STAFFELNR"));
String[] indexArray = indexReader.readLine().split(";");
// Create list with unfiltered values and remove unwanted ones
List<String> resultList = new ArrayList<>(indexArray);
resultList.removeAll(namesToFilter);
// Do with result whatever you want
for (String s : resultList)
System.out.println(s);
With Array you can use contains function but after converting it to be ArrayList, the contains function will check if the ArrayList contains a specific value.
for (int i =0; i<indexArray.length; i++) {
if (!Arrays.asList(namesToLookFor).contains(indexArray[i]))
System.out.println(indexArray[i]);
}

How to create multiple string and integer values from one line in Java using arrays?

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(":");

Java split() into new String[]

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

How to convert a String into an ArrayList?

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(","));

Categories

Resources