I have a String like this:
["http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"]
How can I convert it into an ArrayList of Strings?
Use Arrays#asList
String[] stringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> stringList = Arrays.asList(stringArray);
In case your string contains braces [] and double quotes "", then you should parse the string manually first.
String yourString = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\", \"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
String[] stringArray = yourString
.substring(1, yourString.length() - 2)
.replace('"', '\0')
.split(",\\s+");
List<String> stringList = Arrays.asList(stringArray);
Try the above if and only if you will always receive your String in this format. Otherwise, use a proper JSON parser library like Jackson.
This would be more appropriate
String jsonArr = "[\"http://www.ebuy.al/Images/dsc/17470_500_400.jpg\",
\"http://www.ebuy.al/Images/dsc/17471_500_400.jpg\"]";
List<String> listFromJsonArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonArr);
for(int i =0 ;i<jsonArray.length();i++){
listFromJsonArray.add(jsonArray.get(i).toString());
}
And don't forget to add json library
You can use simple CSV parser if you remove the first and last brackets ('[',']')
Something like this:
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
Method 1: Iterate through the array and put each element to arrayList on every iteration.
Method 2: Use asList() method
Example1:
Using asList() method
String[] urStringArray = { "http://www.ebuy.al/Images/dsc/17470_500_400.jpg", "http://www.ebuy.al/Images/dsc/17471_500_400.jpg"}
List<String> newList = Arrays.asList(urStringArray);
Example2
Using simple iteration
List<String> newList = new ArrayList<String>();
for(String aString:urStringArray){
newList.add(aString);
}
Related
I have the below input string:
"["role_A","role_B","role_C"]"
I want to convert it to a list/array of strings containing all values(role_A, role_B, role_C).
I've done using the below code:
String allRoles = roles.replace("\"","").replaceAll("\\[", "").replaceAll("\\]","").split(",");
Can anyone please suggest more cleaner or better way to do it using Java8!
Existing example and ones with replacing quotes can break if there are quotes in the strings themselves. You can use JSONArray to parse it and then convert to a list if needed
String x = "[\"role_A\",\"role_B\",\"role_C\"]";
JSONArray arr = new JSONArray(x);
List<String> list = new ArrayList<String>();
for (Object one : arr) {
list.add((String)one);
}
System.out.println(list); //prints [role_A, role_B, role_C]
System.out.println(list.size()); //prints 3
json.jar can be found in the Maven repo
String s = "[\"role_A\",\"role_B\",\"role_C\"]";
String[] res = s.split("\\[")[1].split(",");
for (String str : res) {
str = str.replace("]", "").replace("\"", "");
}
Resulting array res is your desired array.
This should do the trick:
String[] arr = s.substring(2, s.length()-2).split("\",\"");
the simplest solution is using GSON or Jackson or any Json converter.
but if you want to do it in manually you can use regex to remove any symbols and split it by comma. But I suggest to use library instead, to make your life easier.
ObjectMapper mapper = new ObjectMapper();
List<String> list = mapper.readValue("[\"role_A\",\"role_B\"]",
mapper.getTypeFactory().constructCollectionType(List.class,
String.class));
One way to achieve this can be as:
List<String> roles = Stream.of(rolesStr.replaceAll("[\"\\[\\]]","").split(",")).collect(Collectors.toList());
System.out.println(roles);
output:
[role_A, role_B, role_C]
I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}
I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));
Please help me to convert ArrayList to String[]. The ArrayList contains values of type Object(VO).
For example,
The problem is that I need to convert a country List to String Array, sort it and then put it in a list. However I am getting a ClassCastException.
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
I have assumed that your country List name is countryList.
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Please help me to convert ArrayList to String[], ArrayList Contains
Values Object(VO) as Values.
As you mentioned that list contains Values Object i.e. your own class you need toString() overridden to make this work correctly.
This code works. Assuming VO is your Value Object class.
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
The snippet of
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
will give you ArrayStoreException due VO is not the String type as required by native method arraycopy subsequently called from toArray one.
In case your ArrayList contains Strings, you can simply use the toArray method:
String[] array = list.toArray( new String[list.size()] );
If that is not the case (as your question is not completely clear on this), you will have to manually loop over all elements
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
What are we doing here:
String[] array is the String array you need to convert your
ArrayList to
list is your ArrayList of VO objects that you have in hand
List#toArray(String[] object) is the method to convert List objects
to Array objects
As correctly suggested by Viktor, I have edited my snippet.
The is a method in ArrayList(toArray) like:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
Then to sort you have::
Arrays.sort(countries);
Then re-converting to List like ::
List<String> countryList = Arrays.asList(countries);
Prior to Java 8 we have the option of iterating the list and populating the array, but with Java 8 we have the option of using stream as well. Check the following code:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);
This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 7 years ago.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Now i want an output from this list as 1,2,3,4 without explicitly iterating over it.
On Android use:
android.text.TextUtils.join(",", ids);
With Java 8:
String csv = String.join(",", ids);
With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", " in your list) - obviously, List#toString will perform a loop to create idList but it does not appear in your code:
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");
import com.google.common.base.Joiner;
Joiner.on(",").join(ids);
or you can use StringUtils:
public static String join(Object[] array,
char separator)
public static String join(Iterable<?> iterator,
char separator)
Joins the elements of the provided array/iterable into a single String containing the provided list of elements.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html
If you want to convert list into the CSV format .........
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
// CSV format
String csv = ids.toString().replace("[", "").replace("]", "")
.replace(", ", ",");
// CSV format surrounded by single quote
// Useful for SQL IN QUERY
String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'")
.replace(", ", "','");
The quickest way is
StringUtils.join(ids, ",");
The following:
String joinedString = ids.toString()
will give you a comma delimited list. See docs for details.
You will need to do some post-processing to remove the square brackets, but nothing too tricky.
One Liner (pure Java)
list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");
Join / concat & Split functions on ArrayList:
To Join /concat all elements of arraylist with comma (",") to String.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);
To split all elements of String to arraylist with comma (",").
String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
Log.i("Result", element);
}
Done
I am having ArrayList of String, which I need to convert to comma separated list, without space. The ArrayList toString() method adds square brackets, comma and space. I tried the Regular Expression method as under.
List<String> myProductList = new ArrayList<String>();
myProductList.add("sanjay");
myProductList.add("sameer");
myProductList.add("anand");
Log.d("TEST1", myProductList.toString()); // "[sanjay, sameer, anand]"
String patternString = myProductList.toString().replaceAll("[\\s\\[\\]]", "");
Log.d("TEST", patternString); // "sanjay,sameer,anand"
Please comment for more better efficient logic.
( The code is for Android / Java )
Thankx.
You can use below code if object has attibutes under it.
String getCommonSeperatedString(List<ActionObject> actionObjects) {
StringBuffer sb = new StringBuffer();
for (ActionObject actionObject : actionObjects){
sb.append(actionObject.Id).append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
return sb.toString();
}
Java 8 solution if it's not a collection of strings:
{Any collection}.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString()
If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));
If you can convert your ArrayList to a FastList, you can get rid of the adapter.
Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));
Note: I am a committer for Eclipse collections.
Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string
Output of this code will be: Veeru,Nikhil,Ashish,Paritosh
instead of output of list [Veeru,Nikhil,Ashish,Paritosh]
String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");
List_name = myNameList.toString().replace("[", "")
.replace("]", "").replace(", ", ",");