How to convert String to ArrayList<String> - java

Let's say I have this String -
string = "AEIOU";
and I wanted to convert it to an ArrayList<String>, where each character is it's own individual String within the ArrayList<String>
[A, E, I, O, U]
EDIT: I do NOT want to convert to ArrayList<Character> (yes, that's very straightforward and I do pay attention in class), but I DO want to convert to an ArrayList<String>.
How would I do that?

transform the String into a char array,
char[] cArray = "AEIOU".toCharArray();
and while you iterate over the array, transform each char into a String, and then add it to the list,
List<String> list = new ArrayList<String>(cArray.length);
for(char c : cArray){
list.add(String.valueOf(c));
}

Loop and use String.charAt(i), to build the new list.

You can do it by using the split method and setting the delimiter as an empty string like this:
ArrayList<String> strings = new ArrayList<>(Arrays.asList(string.split("")));

First you have to define the arrayList and then iterate over the string and create a variable to hold the char at each point within the string. then you just use the add command. You will have to import the arraylist utility though.
String string = "AEIOU";
ArrayList<char> arrayList = new ArrayList<char>();
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
arrayList.add(c);
}
The import statement looks like : import java.util.ArrayList;
To set it as a string arrayList all you have to do is convert the char variables we gave you and convert it back to a string then add it: (And import the above statement)
ArrayList<String> arrayList = new ArrayList<String>();
String string = "AEIOU"
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
String answer = Character.toString(c);
arrayList.add(answer);
}

Since everyone is into doing homework this evening ...
String myString = "AEIOU";
List<String> myList = new ArrayList<String>(myString.length());
for (int i = 0; i < myString.length(); i++) {
myList.add(String.valueOf(myString.charAt(i)));
}

For a single line answer use the following code :
Arrays.asList(string .toCharArray());

Kotlin approach:
fun String.toArrayList(): ArrayList<String> {
return ArrayList(this.split("").drop(1).dropLast(1))
}
var letterArray = "abcd".toArrayList()
print(letterArray) // arrayListOf("a", "b", "c", "d")

Related

Take a List of Strings and double each character in an arraylist

I am trying to double each letter in a list of Strings in an array loop.
For example:
["abc","def"] --> ["aabbcc","ddeeff"]
ArrayList<String> aa;
aa = new ArrayList<String>();
String res = "";
for(int i=0;i<words.size();i++){
char at = aa.get(i);
res=res+at+at;
}
return res;
I am still new to coding and as you can see, my code is a mess. Help is appreciated. Thanks in advance
You some problems with your implementation:
You interact over words array but uses the index over the aa. As it was never added items to it, you will get an ArrayIndexOutOfBoundsException.
You issue a return res but this will return only one string, not an array of words.
According to your example this can be done this way:
public static ArrayList<String> doubleWords(ArrayList<String> input) {
ArrayList<String> result = new ArrayList<>();
for (String string : input) {
String word = "";
for (int i = 0; i < string.length(); i++) {
word += ""+string.charAt(i)+string.charAt(i);
}
result.add(word);
}
return result;
}
Your output for an ArrayList with [abc, def] will be [aabbcc, ddeeff].
You need to iterate through your list of words and then for each word in the list iterate through the characters in the string, like so:
public ArrayList<String> doubleWords(ArrayList<String> words) {
ArrayList<String> doubledWords = new ArrayList<String>();
for (String word : words) {
String newWord = "";
for (int i=0; i<word.length(); i++) {
newWord = newWord + word.substring(i, i+1) + word.substring(i, i+1);
}
doubledWords.add(newWord);
}
return doubledWords;
}
Since Java 8 this can also be achieved in the following way:
String input = "abc";
StringBuilder builder = new StringBuilder();
input.chars().forEach(value -> builder.append((char)value).append((char)value));
Remeber to convert the int value back to a char before you append it.
Output for above program:
System.out.println(builder.toString());
// aabbcc
//response list
ArrayList<String> aa;
aa = new ArrayList<String>();
StringBuilder sb = new StringBuilder() ;
String word;
// iterate list of words
for(int i=0; i < words.size(); i++){
//get word
word = words.get(i);
//iterate each character in word
for(int j =0; j < words; j++) {
//append each char twice in StringBuilder
sb.append(word[j).append(word[j]);
}
//add word to output list
aa.add(sb.toString());
//empty StringBuilder for next word
sb.setLength(0);
}
return aa;
It can be done only by java stream api without any temporary variables:
List<String> result = listOfWords.stream().
map(value -> String.valueOf( // new result String(doubled word)
value.chars() // get chars for each original string
.mapToObj(i-> (char)i) // cast each char from int to char type
.map(c -> String.valueOf(new char[]{c, c})) // create doubled char string
.collect(Collectors.joining()))) // concatenate all doubled chars
.collect(Collectors.toList()); // collect result to list

Modify String objects in a static array

I want to make a for-loop to add a letter to each string object in my list. I'm just not sure how to edit the objects in the list and not the actual list.
for instance, if I wanted to add "ing" to the end of each object in my list..
I feel like it's something simple, but I've been looking through oracle forever and haven't been able to figure it out if anyone can point me in the right direction?
I could use any kind of list really.. just anything that works.
I was thinking something like,
String[] stringArray = tools.toArray(new String[0]);
for (int i = 0; i < stringArray.length; i++)
{
stringArray[i] = stringArray[i].*part that would modify would go here*
}
You cannot edit a String. They are immutable. However, you can replace the entry in the list.
ArrayList<String> list = new ArrayList<>();
list.add("load");
list.add("pull");
for (int i = 0; i < list.size(); ++i) {
list.set(i, list.get(i) + "ing");
You updated your question to specify a static array:
stringArray[i] = stringArray[i] + "ing";
The right side of the assignment is performing a String concatenation which can be done with the + operator in Java.
You can use StringBuilder for this purpose.
public static void addIng(String[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.setLength(0);
sb.append(arr[i] + "ing");
arr[i] = sb.toString();
}
}
Strings are immutable in java; they can't be modified once created.
Here it seems you have a few options; you can create a method that takes your list and returns a new list, by appending 'ing' to the end of each string in the list.
Alternatively, if you need to keep a reference to the original list, you can loop over the contents of the list (ArrayList?) and pop each string out, create a new string with the appended 'ing', and replace in the list.
Something like
List<String> list = new ArrayList<>();
list.add("testing");
for(String s:list){
s=s+"ing";
}
Please take a look below samples.
//Java 8 code.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = oldList.stream().map(str -> new StringBuilder(str).append("ing").toString()).collect(Collectors.toList());
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]
// Java 7 or below.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = new LinkedList<String>();
for (String str : oldList) {
newList.add(new StringBuilder(str).append("ing").toString());
}
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]

How to convert an Arraylist of Characters to an array of chars

I am working on a project when I create ArrayList of characters(ArrayList<Character>) to dynamically add elements to the list.
How do I, then, convert this into an array of char? (This is needed as part of the later functions.)
I would recommend just iterating through the entire arraylist and adding the chars to your array.
char[] myCharArray = new char[list.size()];
for(int i = 0; i < list.size(); i++) {
myCharArray[i] = list.get(i);
}
You could just make a quick method that would do that for you:
public static char[] convert(final List<Character> list){
final char[] array = new char[list.size()];
for(int i = 0; i < array.length; i++)
array[i] = list.get(i);
return array;
}
Try this:
public char[] toArray(List<Character> list){
char[] toReturn = new char[list.size()];
int i = 0;
for(char c : list)
toReturn[i ++] = c;
return toReturn;
}
You could easily iterate through the array like the other answers have specified, but this is a different way to do it:
Character[] array = new Character[list.size()];
list.toArray(array);
The only problem with this is it doesn't work for the primitive type char so you have to use the wrapper class Character
It doesn't change anything, except that you're using a Character class array vs. a char array.
Example:
public static void main(String args[])
{
List<Character> list = new ArrayList<Character>();
list.add('a');
list.add('x');
list.add('j');
Character[] array = new Character[list.size()];
list.toArray(array);
System.out.println(Arrays.toString(array));
}
Output:
[a, x, j]
Take a look at the Docs for information on ArrayList methods.

Split id and add to array

I have to split off the last two characters of an ID, the id may vary in length. example 56427R1 and R00220P3. Once the last two characters are split off, I need to add the first set of characters and the last two characters to an ArrayList. Thanks in advance.
I've tried the following
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
but was having trouble keeping the last 2 characters while removing the first half.
Resolved, repaired with the following code
ArrayList<String> list = new ArrayList<String>();
list.add(clientValue.substring(clientValue.length()-2));
list.add(clientValue.substring(0, clientValue.length()-2));
Use String.substring() with String.length() to split the string.
Use ArrayList<String>.add() to append to an ArrayList.
EDIT:
the code you have posted is correct: clientValue is not modified by the call to clientValue.substring() but returns a new String instance. Java String are immutable.
To complete your code:
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
list.add(clientValue.substring(clientValue.length()-2));
string tmp = "56427R1";
ArrayList<String> arrList = new ArrayList()<String>;
arrayList.add(tmp.substring(tmp.length() - 2));
arrayList.add(tmp.substring((tmp.length() - 2), tmp.length()));
You can do it easily like this:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
ArrayList<String> list = new ArrayList<String>;v
list.add(myID.substring((myID.length()-2)));
list.add(extractedID);
UPDATE:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
char[] a = extractedID.toCharArray();
char[] b = myID.substring(myID.length()-2).toCharArray();
ArrayList<Character> list = new ArrayList<Character>();
for(int i = 0; i < b.length; i++)
list.add(b[i]);
for(int j = 0; j < a.length; j++)
list.add(a[j]);

How to convert a char array to a string array

How do you convert a char array to a string array? Or better yet, can you take a string and convert it to a string array that contains each character of the string?
Edit: thanks #Emiam! Used his code as a temp array then used another array to get rid of the extra space and it works perfectly:
String[] tempStrings = Ext.split("");
String[] mStrings = new String[Ext.length()];
for (int i = 0; i < Ext.length(); i++)
mStrings[i] = tempStrings[i + 1];
Or better yet, can you take a string and convert it to a string array
that contains each character of the string?
I think this can be done by splitting the string at "". Like this:
String [] myarray = mystring.split("");
Edit:
In case you don't want the leading empty string, you would use the regex: "(?!^)"
String [] mySecondArray = mystring.split("(?!^)");
Beautiful Java 8 one-liner for people in the future:
String[] array = Stream.of(charArray).map(String::valueOf).toArray(String[]::new);
I have made the following test to check Emiam's assumption:
public static void main(String[] args) {
String str = "abcdef";
String [] array = str.split("");
}
It works, but it adds an empty string in position 0 of the array.
So array is 7 characters long and is { "", "a", "b", "c", "d", "e", "f" }.
I have made this test with Java SE 1.6.
brute force:
String input = "yourstring";
int len = input.length();
String [] result = new String[len];
for(int i = 0; i < len ; i ++ ){
result[i] = input.substring(i,i+1);
}
This will give string[] as result, but will have only one value as below
String[] str = {"abcdef"};
// char[] to String[]
String[] sa1 = String.valueOf(cArray).split("");

Categories

Resources