How to convert an ArrayList<Character> to a String in Java?
The List.toString method returns it as [a,b,c] string - I want to get rid of the brackets (etcetera) and store it as abc.
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
Setting the capacity of the StringBuilder to the list size is an important optimization. If you don't do this, some of the append calls may trigger an internal resize of the builder.
As an aside, toString() returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
Here a possible one-line solution using Java8 streams.
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.reduce((acc, e) -> acc + e)
.get();
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.reduce((acc, e) -> acc + e)
.get();
UPDATE (following comment below):
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.collect(Collectors.joining());
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.collect(Collectors.joining());
Note that the map(e->e.toString()) step in the above solutions will create a temporary string for each character in the list. The strings immediately become garbage. So, if the performance of the conversion is a relevant concern, you should consider using the StringBuilder approach instead.
How about this, Building the list
List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
Actual code to get String from List of Character:
String word= new String();
for(char c:charsList){
word= word+ c;
}
System.out.println(word);
Still learning if there is a misake point out.
You can do it using toString() and RegExp without any loops and streams:
List<Character> list = Arrays.asList('a', 'b', 'c');
String s = list.toString().replaceAll("[,\\s\\[\\]]", "");
Assuming you have a following list:
final ArrayList<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
This will yield hello (I am using org.apache.commons.lang.ArrayUtils helper class):
final Character[] charactersArray =
charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));
Using join of a Joiner class:
// create character list and initialize
List<Character> arr = Arrays.asList('a', 'b', 'c');
String str = Joiner.on("").join(arr);
System.out.println(str);
Use toString then remove , and spaces
import com.google.common.base.Joiner;
....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o');
// remove [] and spaces
String str = arr.toString()
.substring(1, 3 * str.size() - 1) //3 bcs of commas ,
.replaceAll(", ", "");
System.out.println(str);
Or by using streams:
import java.util.stream.Collectors;
...
// using collect and joining() method
String str = arr.stream().map(String::valueOf).collect(Collectors.joining());
Easiest is to loop through.
List<String> strings = new ArrayList<String>();
// populate strings
StringBuilder builder = new StringBuilder();
for(String string : strings) {
builder.append(string).append(',');
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
System.out.println(builder);
Many solutions available. You can iterate over the chars and append to a StringBuilder, then when finished appending, call .toString on the StringBuilder.
Or use something like commons-lang StringUtils.join from the apache commons-lang project.
a tiny complement to #waggledans 's answer
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());
which e->e.toString() can be replaced by Object::toString
String str = chars.stream().map(Object::toString).collect(Collectors.joining());
I consider this an easy and smart way
// given list containing the chars
List<Character> arr = Arrays.asList('a', 'b', 'c');
//convert list to string
String output = arr.toString().replaceAll("[ ,]","")
.substring(1, tmpArr.length()-1);
Explanation:
// convert to string.
String str = arr.toString(); // result is "[a ,b ,c]"
// get rid of the start and the end char i.e '[' & ']'
str = str.substring(1, tmpArr.length()-1); //result is "a ,b ,c"
// replace <space> and ','
str = str.replaceAll(" ,","") "ABC"
I would say :
public String arayListToString(ArrayList arrayList){
StringBuffer b = new StringBuffer();
for(String s : arrayList){
b.append(s);
b.append(",");
}
return b.toString();
}
private void countChar() throws IOException {
HashMap hashMap = new HashMap();
List list = new ArrayList();
list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
list.stream().forEach(e -> {
hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
hashMap.computeIfAbsent(e, (V) -> 1);
});
System.out.println(hashMap);
}
Related
I write a program replacing String in which words are delimited by '-' or '_' (word1-word2-word3... or word1_word2_word3... or any combination of those), to camel case format: word1Word2Word3...
I wanted to do it like this:
str.replaceAll("[-_]([a-zA-Z0-9])", "$1".toUpperCase()); and half of it sorta works: I get resutl of: word1word2word3... - looks like, toUpperCase() didn't have any effect, so my questions are: why is it so and how to make it work - preferably using replaceAll()
Sample input: word1_word2_word3
Expected output: word1Word2Word3
Use the replaceAll(Function<MatchResult, String>) method of Matcher:
str = Pattern.compile("[-_]([a-zA-Z0-9])")
.matcher(str)
.replaceAll(mr -> mr.group(1).toUpperCase());
See live demo showing that:
String str = "word1_word2-word3";
str = Pattern.compile("[-_]([a-zA-Z0-9])")
.matcher(str)
.replaceAll(mr -> mr.group(1).toUpperCase());
System.out.println(str);
Outputs:
word1Word2Word3
Here is working solution for your mentioned problem :
public static void main(String[] args) {
char[] deliminators = {'-', '_'};
String input = "word1-word2-word3_word1_word2_word3";
char[] output = "word1-word2-word3_word1_word2_word3".toCharArray();
int index = 0;
for (char element : input.toCharArray()) {
if (ArrayUtils.contains(deliminators, element)) {
ArrayUtils.remove(output, index);
index++;
output[index] = Character.toUpperCase(output[index]);
continue;
}
index++;
}
output[0] = Character.toUpperCase(output[0]);
String.valueOf(output).replaceAll("-", "").replaceAll("_", "");
System.out.println(String.valueOf(output).replaceAll("-", "").replaceAll("_", ""));
}
Kindly acknowledge , it should work directly for your use-case.
Excuse the brevity, currently on mobile.
I have a string array of values ABC, DEF, GHI that I would like to change to capitalized form: Abc, Def, Ghi
My code looks something like this:
import org.apache.commons.lang3.text.WordUtils;
....
final String[] split = stringToConvert.split(", ");
final StringBuilder sb = new StringBuilder();
for ( String s : split) {
//s = WordUtils.capitalizeFully(s.toLowerCase());
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(WordUtils.capitalizeFully(s.toLowerCase()));
}
return sb.toString();
The first value is always abc, but the second and following ones are correct, e.g. Def, Ghi. I don't know why the first value stays lowercase.
Any help would be appreciated!
Check your code again.
StringBuilder buf = new StringBuilder();
for (String str : new String[]{"ABC", "DEF", "GHI"})
buf.append(WordUtils.capitalizeFully(str.toLowerCase()));
System.out.println(buf);
Prints AbcDefGhi, as expected.
It could be simplier, if you use Stream:
String res = Stream.of("ABC", "DEF", "GHI")
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining(", ")); // if you want to split words with comma
Your code should work.
May I however suggest using a stream instead?
String concatenatedString = Arrays.stream(array)
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining());
Which, with appropriate static imports fits well on one line without losing readability:
String concatenatedString = stream(array).map(WordUtils::capitalizeFully).collect(joining());
Note that joining() uses a StringBuilder iternally, so you don't need to worry about performance here. Also, joining() allows you to choose which string you want to delimit the content of the stream with, in this case I chose an empty string, which would result in AbcDefGhi.
This should do :
String[] stringToSplit = {"ABC", "DEF", "GHI"};
StringBuilder sb = new StringBuilder();
for(String s: stringToSplit) {
sb.append(s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase());
}
Update: I'm tired...
The first character was actually a [ from the array instead of "a", thus the a was never capitalized
Thanks all, and sorry for wasting your time
I am struggling with how to actually do this. Say I have this string
"This Str1ng i5 fun"
I want to replace the '1' with "One" and the 5 with "Five"
"This StrOneng iFive fun"
I have tried to loop thorough the string and manually replace them, but the count is off. I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:
char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();
for(char character: stringAsCharArray) {
charArraylist.add(character);
}
int counter = startPosition;
while(counter < endPosition) {
char temp = charArraylist.get(counter);
String tempString = Character.toString(temp);
if(Character.isDigit(temp)){
char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number
charArraylist.remove(counter);
int addCounter = counter;
for(char character: tempChars) {
charArraylist.add(addCounter, character);
addCounter++;
}
counter += tempChars.length;
endPosition += tempChars.length;
}
counter++;
}
I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. Am I wrong here?
String[][] arr = {{"1", "one"},
{"5", "five"}};
String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}
System.out.println(str);
This would help you to replace multiple words with different text.
Alternatively you could use chained replace for doing this, eg :
str.replace(1, "One").replace(5, "five");
Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)
You can do
string = string.replace("1", "one");
Don't use replaceAll, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here).
Despite the name, replace also replaces all occurrences.
Since Strings are immutable, be sure to assign the result value somewhere.
Try the below:
string = string.replace("1", "one");
string = string.replace("5", "five");
.replace replaces all occurences of the given string with the specified string, and is quite useful.
so I have the string "116,101,115,116,49,50,51,52" and I want to convert it from ASCII decimals to ASCII letters. This is the code I'm using to do that:
String charInts = "116,101,115,116,49,50,51,52";
String[] tokenizedCharInts = charInts.split(",");
String phrase = "";
for (int i = 0; i < tokenizedCharInts.length; i++) {
int digit = Integer.parseInt(tokenizedCharInts[i]);
phrase += (char) digit;
}
System.out.println(phrase);
It works so I'm fairly happy with it, but I'm wondering if anyone knows a more elegant way of doing this instead, perhaps without using that for loop (having to convert each split string to an int, then a char, then append it, for every small sub-string, makes me feel like their must be a cleaner solution).
Using StringBuilder and other for maybe? :
String charInts = "116,101,115,116,49,50,51,52";
String[] tokenizedCharInts = charInts.split(",");
StringBuilder phrase = new StringBuilder();
for (String a : tokenizedCharInts) {
phrase.append((char)Integer
.parseInt(a));
}
System.out.println(phrase);
You can use an enhanced for loop, since you don't need the array element index.
You should use a StringBuilder to accumulate the string instead of String phrase, to avoid repeated string construction.
You can use Scanner and StringBuilder combo : (no need to split the String and loop though it.)
String charInts = "116,101,115,116,49,50,51,52";
Scanner scanner=new Scanner(charInts);
scanner.useDelimiter(",");
StringBuilder sb=new StringBuilder();
while (scanner.hasNextInt()) {
sb.append((char)scanner.nextInt());
}
scanner.close();
System.out.println(sb.toString());
Java-8 solution:
String charInts = "116,101,115,116,49,50,51,52";
String phrase = Arrays.stream(charInts.split(",")).mapToInt(Integer::parseInt)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(phrase);
IF this fits your use-case:
char[] charInts = new char[] { 116,101,115,116,49,50,51,52 };
String s = new String(charInts);
Yes, Java provides an elegant, single-line solution using Streams API.
String charInts = "116,101,115,116,49,50,51,52";
StringBuilder sb = new StringBuilder();
Arrays.stream(charInts.split(","))
.map(Integer::parseInt)
.map(Character::toChars)
.forEach(sb::append);
System.out.println(sb.toString());
I want to print a string that is converted from a collection of characters. But I want to eliminate the commas (,) and square brackets([]) from the printing string.
List<Character> word_to_show = new ArrayList<Character>();
for(char ch:jumbled_word.toCharArray()){
word_to_show.add(ch);
}
Collections.shuffle(word_to_show);
for (Object ch: word_to_show)
System.out.print((Character) ch );
System.out.println();
send_to_timer = word_to_show.toString();
I have come to this. It works but prints the string as, say for eg, [a, b, c]
You can use replace()
string.replace(",","").replace("[","").replace("]","")
Demo
If you have a real Collection containing characters, you can simply iterate that collection - and use a StringBuilder to append all those characters that you want to have in your final string; like:
StringBuilder validChars = new StringBuilder();
for (Character chr : yourCollection) {
if (chr != ' ' && chr != ',') {
validChars.append(chr);
}
}
First turning all characters into a string, then use replace() to create a new string with less characters seems a bit inefficient.