Java: Convert List<Integer> to String - java

How can I convert List<Integer> to String? E.g. If my List<Integer> contains numbers 1 2 and 3 how can it be converted to String = "1,2,3"? Every help will be appreciated.

I think you may use simply List.toString() as below:
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
String listString = intList.toString();
System.out.println(listString); //<- this prints [1, 2, 3]
If you don't want [] in the string, simply use the substring e.g.:
listString = listString.substring(1, listString.length()-1);
System.out.println(listString); //<- this prints 1, 2, 3
Please note: List.toString() uses AbstractCollection#toString method, which converts the list into String as above

In vanilla Java 8 (streams) you can do
// Given numberList is a List<Integer> of 1,2,3...
String numberString = numberList.stream().map(String::valueOf)
.collect(Collectors.joining(","));
// numberString here is "1,2,3"

With Guava:
String s = Joiner.on(',').join(integerList);

One way would be:
Iterate over list, add each item to StringBuffer (or) StringBuilder and do toString() at end.
Example:
StringBuilder strbul = new StringBuilder();
Iterator<Integer> iter = list.iterator();
while(iter.hasNext())
{
strbul.append(iter.next());
if(iter.hasNext()){
strbul.append(",");
}
}
strbul.toString();

Just to add another (of many) options from a popular library (Apache Commons):
import org.apache.commons.lang3.StringUtils;
String joinedList = StringUtils.join(someList, ",");
See documentation: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join-java.lang.Iterable-java.lang.String-
An elegant option from others' comments (as of Java 8):
String joinedList = someList.stream().map(String::valueOf).collect(Collectors.joining(","));

Related

How to convert comma separated and double quoted words string to list/array of strings in Java

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]

ArrayList to String with separated by Comma [duplicate]

This question already has answers here:
The simplest way to comma-delimit a list?
(30 answers)
Closed 6 years ago.
I have an ArrayList and I want to output completely as a String with separated by comma.
My code is
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (String s : list)
{
listString += s + ",";
}
System.out.println(listString);
But the output is one,two,three, and i want one,two,three without using replace method.
I am using JAVA
Using Java 8:
List<String> list = Arrays.asList(array);
String joinedString = String.join(",", list);
In Java 8+ you could use a StringJoiner (and you can use Arrays.asList(T...) to initialize your List). Something like,
List<String> list = Arrays.asList("one", "two", "three");
StringJoiner sj = new StringJoiner(",");
for (String s : list) {
sj.add(s);
}
System.out.println(sj.toString());
Output is (as requested)
one,two,three
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
String listString = "";
for (int i=0;i<list.size()-1;i++)
listString += list.get(i) + ",";
System.out.println(listString+list.get(list.size()-1));
}
}
Output:
one,two,three
http://ideone.com/PkAOOq
Just use String.substring. Here you go:
listString = listString.substring(0, listString.length() - 1);
You can use java.util.StringJoiner for this, instead of a List:
StringJoiner joiner = new StringJoiner(",");
joiner.add("one");
joiner.add("two"),
joiner.add("three");
String listString = joiner.toString();
If you are not using Java8, then consider using StringBuilder. Then your final string can be:
System.out.println(listString.substring(0, listString.length() - 1));
For a pre Java 8 solution, since the default toString() gives you [one, two, three].
String s = list.toString();
s = s.substring(1, s.length()-1);
try
list.toString().replace("[", "").replace("]", "");

Convert a List of Strings into a single String using ArrayUtils in java

I have below code
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
Need output as "one,two,three" in a single string using Array Utils. Need a single line solution.
Use join
String joined2 = String.join(",", test );
You can't do this with ArrayUtils. You can use Apache's StringUtils join function to get the result you want.
// result is "one,two,three"
StringUtils.join(test, ',');
If you don't want to use a library, you can create this function:
public static String joiner(List<String> list, String separator){
StringBuilder result = new StringBuilder();
for(String term : list) result.append(term + separator);
return result.deleteCharAt(result.length()-separator.length()).toString();
}
If you must use ArrayUtils then you could use List.toArray(T[]) (because ArrayUtils is for arrays) and a regular expression to remove { and } on one line like
List<String> test = new ArrayList<>(Arrays.asList("one", "two", "three"));
System.out.println(ArrayUtils.toString(test.toArray(new String[0]))
.replaceAll("[{|}]", ""));
Output is (as requested)
one,two,three
The String.join(CharSequence, Iterable<? extends CharSequence>) suggested by #Vishnu's answer offers a solution that eschews ArrayUtils (but is arguable better, assuming you can use it) with
String joined2 = String.join(",", test);
System.out.println(joined2);
which outputs the same.
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two");
test.add("three");
Iterator it = test.iterator();
while(it.hasNext()){
String s=it.next();
StringBuilder sb = new StringBuilder();
sb.append(s);
}

How to convert a List<String> into a comma separated string without iterating List explicitly [duplicate]

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

Convert List<String> to List<Integer> directly

After parsing my file " s" contains AttributeGet:1,16,10106,10111
So I need to get all the numbers after colon in the attributeIDGet List. I know there are several ways to do it. But is there any way we can Directly convert List<String> to List<Integer>.
As the below code complains about Type mismatch, so I tried to do the Integer.parseInt, but I guess this will not work for List. Here s is String.
private static List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
attributeIDGet = Arrays.asList(s.split(":")[1].split(","));
}
Using Java8:
stringList.stream().map(Integer::parseInt).collect(Collectors.toList());
No, you need to loop over the array
for(String s : strList) intList.add(Integer.valueOf(s));
Using lambda:
strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());
You can use the Lambda functions of Java 8 to achieve this without looping
String string = "1, 2, 3, 4";
List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
Guava Converters do the trick.
import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;
final Iterable<Long> longIds =
Longs.stringConverter().convertAll(
Splitter.on(',').trimResults().omitEmptyStrings()
.splitToList("1,2,3"));
No, you will have to iterate over each element:
for(String number : numbers) {
numberList.add(Integer.parseInt(number));
}
The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car object and a Person object. You can't convert a List<Car> into a List<Person> directly since it doesn't really make sense.
If you use Google Guava library this is what you can do, see Lists#transform
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
attributeIDGet =
Lists.transform(attributeIDGetS, new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
};
});
}
Yep, agree with above answer that's it's bloated, but stylish. But it's just another way.
Why don't you use stream to convert List of Strings to List of integers?
like below
List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
"50", "60", "70"));
List<Integer> integerList = stringList.stream()
.map(Integer::valueOf).collect(Collectors.toList());
complete operation could be something like this
String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
Arrays.asList(s.replace("AttributeGet:", "").split(","))
.stream().map(Integer::valueOf).collect(Collectors.toList())
: new ArrayList<Integer>();
If you're allowed to use lambdas from Java 8, you can use the following code sample.
final String text = "1:2:3:4:5";
final List<Integer> list = Arrays.asList(text.split(":")).stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
System.out.println(list);
No use of external libraries. Plain old new Java!
Using Streams and Lambda:
newIntegerlist = listName.stream().map(x->
Integer.valueOf(x)).collect(Collectors.toList());
The above line of code will convert the List of type List<String> to List<Integer>.
I hope it was helpful.
No, there is no way (that I know of), of doing that in Java.
Basically you'll have to transform each entry from String to Integer.
What you're looking for could be achieved in a more functional language, where you could pass a transformation function and apply it to every element of the list... but such is not possible (it would still apply to every element in the list).
Overkill:
You can, however use a Function from Google Guava (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html) to simulate a more functional approach, if that is what you're looking for.
If you're worried about iterating over the list twice, then instead of split use a Tokenizer and transform each integer token to Integer before adding to the list.
Here is another example to show power of Guava. Although, this is not the way I write code, I wanted to pack it all together to show what kind of functional programming Guava provides for Java.
Function<String, Integer> strToInt=new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
}
};
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet =(s.contains("AttributeGet:"))?
FluentIterable
.from(Iterables.skip(Splitter.on(CharMatcher.anyOf(";,")).split(s)), 1))
.transform(strToInt)
.toImmutableList():
new ArrayList<Integer>();
Use Guava transform method as below,
List intList = Lists.transform(stringList, Integer::parseInt);
import java.util.Arrays;
import java.util.Scanner;
public class reto1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double suma = 0, promedio = 0;
String IRCA = "";
int long_vector = Integer.parseInt(input.nextLine());
int[] Lista_Entero = new int[long_vector]; // INSTANCE INTEGER LIST
String[] lista_string = new String[long_vector]; // INSTANCE STRING LIST
Double[] lista_double = new Double[long_vector];
lista_string = input.nextLine().split(" "); // INPUT STRING LIST
input.close();
for (int i = 0; i < long_vector; i++) {
Lista_Entero[i] = Integer.parseInt(lista_string[i]); // CONVERT INDEX TO INDEX FROM STRING UNTIL INTEGER AND ASSIGNED TO NEW INTEGER LIST
suma = suma + Lista_Entero[i];
}

Categories