Convert ArrayList of Integers to String Java - java

I want to convert an ArrayList of Integers to a single string.
For example:
List<Integers> listInt= new ArrayList();
String str = "";
listInt.add(1);
listInt.add(2);
listInt.add(3);
// I want the output to be: str = "123";

String numberString = listInt.stream().map(String::valueOf)
.collect(Collectors.joining(""));
//You can pass a delimiter if you want to the joining() function, like a comma. ","

Try this, the simplest way:
List<Integer> listInt = Arrays.asList(1,2,3);
String str = "";
StringBuilder builder = new StringBuilder();
for(Integer item : listInt)
builder.append(item);
str = builder.toString();
System.out.println(str);

Related

Create ArrayList from comma separated String without whitespace

Say I have a String with randomly placed spaces and commas around other characters.
String str = "item1 , it em 2, ite m 3"
How do I get an ArrayList with the items like
[item1, item2, item3]
Use the following:
String str = "item1 , it em 2, ite m 3"
String[] splitArray = str.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String s:splitArray)
{
list.add(s.replace(" ", ""));
}
just for fun :-)
import org.apache.commons.lang3.StringUtils;
String inputString = "item1 , it em 2, ite m 3";
List<String> stringList = Arrays.stream(StringUtils.deleteWhitespace(inputString).split(",")).collect(Collectors.toList());
Here's another solution
//Given string
String str = "item1 , it em 2, ite m 3";
//Match one or more occurrence of space in the string and replace by empty
String pattern = "\\s+";
str = str.replaceAll(pattern, "");
//Split by , and convert to ArrayList
List<String> items = Arrays.asList(str.split(","));
for(String temp: items)
System.out.println(temp);
Using Java 8 's parallelSetAll
String str = "item1 , it em 2, ite m 3";
String[] stringlist = str.split(",");
Arrays.parallelSetAll(stringlist, (i) -> stringlist[i].replaceAll(" ",""));

How to remove last character string in java

I want to remove comma in last data.
example:
i have code:
StringBuilder temp = new StringBuilder();
for (int i=0; i<allLines.size(); i++){
StringBuilder temp2 = new StringBuilder();
String[] abc = line.split("\t");
temp2.append("{");
temp2.append("id: \""+abc[0]+"\",");
temp2.append("name: \""+abc[1]+"\",");
temp2.append("},");
temp.append(temp2.toString());
}
System.out.println("result : "+temp.toString());
ihave code and result:
{id: "1", name: "Jhames"},{id: "2", name: "Richard"},
but i want result:
{id: "1", name: "Jhames"},{id: "2", name: "Richard"}
Just use the new java 8 StringJoiner! (And other nifty Java methods)
Example:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
It also supports streams in the form of Collectors.joining(",")
Full example:
public static void main(String[] args) {
String input = "1\tJames\n2\tRichard";
String output = Arrays.stream(input.split("\n"))
.map( i -> String.format("{ id: \"%s\", name: \"%s\" }", i.split("\t")))
.collect(Collectors.joining(","));
//prints: { id: "1", name: "James" },{ id: "2", name: "Richard" }
System.out.println(output);
}
You can avoid appending it in the first place :
for (int i=0; i<allLines.size(); i++){
StringBuilder temp2 = new StringBuilder();
String[] abc = line.split("\t");
temp2.append("{");
temp2.append("id: \""+abc[0]+"\",");
temp2.append("name: \""+abc[1]+"\",");
temp2.append("}");
if (i<allLines.size()-1)
temp2.append(",");
temp.append(temp2.toString());
}
Alternatively add this after your for loop
temp.setLength(temp.length() - 1);
which requires no constant index checking in your code
You can use deleteCharAt() method.
StringBuilder s = new StringBuilder("{id: \"1\", name: \"Jhames\"},{id: \"2\", name: \"Richard\"},");
System.out.println(s.deleteCharAt(s.lastIndexOf(",")));
First of all you don't need two StringBuilders, so instead of
StringBuilder sb1 = ..
for(..){
StringBuilder sb2 = ...
//fill sb2
sb1.append(sb2);
}
you should use
StringBuilder sb1 = ..
for(..){
//add all you want to sb1
sb1.append(..)
sb1.append(..)
}
Next thing is that you don't ever want to do
sb.appent("foo" + x + "bar");
because it is same as
sb.append(new StringBuilder("foo").append(x).append("bar").toString())
which is very ineffective because:
you are creating separate StringBuilder each time you do so
this new StringBuilder needs to unnecessary call toString method which has to copy all characters to new String which will later be copied to builder, instead of calling append(StringBuilder) and copy its characters directly.
So instead of sb.appent("foo" + x + "bar"); always write
sb.appent("foo").append(x).append("bar");
Now lets go back to your main problem. Since your code doesn't have declaration of line variable I am assuming that by
String[] abc = line.split("\t");
you mean
String[] abc = allLines.get(i).split("\t");
So your code can look like
StringBuilder temp = new StringBuilder();
for (int i = 0; i < allLines.size(); i++) {
String[] abc = allLines.get(i).split("\t");
temp.append("{id: \"").append(abc[0]).append("\", ");
temp.append("name: \"").append(abc[1]).append("\"}");
if (i < allLines.size() - 1)
temp.append(", ");
}
System.out.println("result : " + temp.toString());
No Java 8 solution:
StringBuilder temp = new StringBuilder();
adder(temp, allLines.get(0));
for (int i=1; i<allLines.size(); i++){
temp.append(",");
adder(temp, allLines.get(i));
}
System.out.println("result : "+temp.toString());
private static void adder(StringBuilder temp,String line){
String[] abc = line.split("\t");
temp.append("{id: \"");
temp.append(abc[0]);
temp.append("\",");
temp.append("name: \"");
temp.append(abc[1]);
temp.append("\"}");
}

Extract String(s) from big String selected by special characters

Let's say I have a String like this:
Hey man, my name is Jason and I like Pizza. #Pizza #Name #Cliche
My question is how to extract all the strings that start with # and put them to another string together?
Check out this tutorial on regex
Try
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)").matcher(string);
while(matcher.find()){
System.out.println(matcher.group(2));
}
EDIT:
As you wanted the other strings as well, you may try
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)|(\\S+)").matcher(string);
StringJoiner hashfull = new StringJoiner(" ");
StringJoiner hashless = new StringJoiner(" ");
while(matcher.find())
if(matcher.group(2) != null)
hashfull.add(matcher.group(2));
else if(matcher.group(3) != null)
hashless.add(matcher.group(3));
System.out.println(hashfull);
System.out.println(hashless);
I found this code working very well for me because I wanted also the rest of the string. Thanks to #Pshemo and #Mormod for helping me with this. Here is the code:
String string = "Hello my name is Jason and I like pizza. #Me #Pizza";
String[] splitedString = string.split(" "); //splits string at spaces
StringBuilder newString = new StringBuilder();
StringBuilder newString2 = new StringBuilder();
for(int i = 0; i<splitedString.length; i++){
if(splitedString[i].startsWith("#")){
newString.append(splitedString[i]);
newString.append(" "); }
else{
newString2.append(splitedString[i]);
newString2.append(" ");
}
}
System.out.println(newString2);
System.out.println(newString);
Maybe you search for something like this:
String string = "ab cd ef"
String[] splitedString = string.split(" "); //splits string at spaces
String newString = "";
for(int i = 0; i<splitedString; i++){
if(splitedString[i].startsWith("#")){
newString += splitedString[i];
}
}
mormod

How to convert String[] to String and vice versa in Android

I want to convert a String Array to String so that later on while retrieving I can parse String to String[] with the help of (,) separator.
String [] ------------> String
//and later
String ---------------> String[]
Can someone guide on how to do this?
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayData == " +arrayData[i]);
// Joining:
String joined = String.join(",", arrayData);
//This will give error "The method join(String, String[]) is undefined for the type String"
}
You can use String.join StringBuilder and String.split:
// Joining:
String joined = String.join(",", stringArr);
StringBuilder buffer = new StringBuilder();
for (String each : stringArr)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
// Splitting:
String[] splitted = joined.split(",");

Xmlparser for html to pdf

This is a small snippet of my code.It works fine but what if I wanted to add a number to each String variable str.
How do I do that?Please help.
Collections.shuffle(arrlist);
for(int i=0;i<nb;i++){
String str = (String) arrlist.get(i);
//worker.parseXHtml(writer, document, new StringReader("<br>"));
worker.parseXHtml(writer, document, new StringReader(str));
}
Try
String str = (String) arrlist.get(i)+String.valueOf(someNumber);
If you want to add i
String str = (String) arrlist.get(i)+String.valueOf(i);
Update
public static void main(String[] args) {
List arrlist = new ArrayList<>();
arrlist.add("tester");
int i = 0;
String str = (String) arrlist.get(i) + String.valueOf(i);
System.out.println(str);
}
o/p:
tester0

Categories

Resources