This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Assigning an array to an ArrayList in Java
java: how to convert this string to ArrayList?
How to convert a String into an ArrayList?
I have this String :
["word1","word2","word3","word4"]
The above text is not an array, but a string returned from server via GCM (Google Cloud Messaging) communication. More specific, inside a GCM class i have this:
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("cabmate");
}
The value of the String message is ["word1","word2","word3","word4"]
Is there a way to convert it in List or ArrayList in Java?
Arrays.asList(String[])
returns a List<String>.
Something like this:
/*
#invariant The "Word" fields cannot have commas in thier values or the conversion
to a list will cause bad field breaks. CSV data sucks...
*/
public List<String> stringFormatedToStringList(String s) {
// oneliner for the win:
return Arrays.asList(s.substring(1,s.length()-1).replaceAll("\"","").split(","));
// .substring removes the first an last characters from the string ('[' & ']')
// .replaceAll removes all quotation marks from the string (replaces with empty string)
// .split brakes the string into a string array on commas (omitting the commas)
// Arrays.asList converts the array to a List
}
String wordString = "[\"word1\", \"word2\", \"word3\", \"word4\"]";
String[] words = wordString.substring(1, wordString.length() - 2).replaceAll("\"", "").split(", ");
List<String> wordList = new ArrayList<>();
Collections.addAll(wordList, words);
This will do what you want. Do note that I purposely split on ", " to remove white space, it may be more prudent to call .trim() on each string in a for-each loop and then add to the List.
Related
ok. Rookie question.
I have a scanned string that i would like to sort using Collections.sort(string).
The string comes from a scanned file that has a bunch of "asdfasdfasdf" in it.
I have scanned the file (.txt) and the scannermethod returns a String called scannedBok;
The string is then added to an ArrayList called skapaArrayBok();
here is the code:
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
strengar.add(scanner());
Collections.sort(strengar);
return (strengar);
}
in my humble rookie brain the output would be "aaadddfffsss" but no.
This is a schoolasigment and the whole purpose of the project is to find the 10 most frequent words in a book. But i can't get it to sort. But i just would like to know why it won't sort the scanned string?
You are sorting the list, not the String. The list has only one element, so sorting it doesn't change anything.
In order to sort the content of the String, convert it to an array of characters, and sort the array.
Collections.sort() sorts the items in a list.
You have exactly one item in your list: the string "aaadddfffsss". There's nothing to sort.
SUGGESTIONS:
1) Read more strings into your collection
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
// Input three strings
strengar.add(scanner());
strengar.add(scanner());
strengar.add(scanner());
// Now sort
Collections.sort(strengar);
... or ...
2) Split the string into characters, and sort the characters.
public ArrayList<String> skapaArrayBok() {
// Get string
String s = scanner());
char[] charArray = s.toCharArray();
Arrays.sort(charArray );
// Return sorted string
return (new String(charArray);
It is correct to sort "strengar", the ArrayList. However, it would not change the ordering of the ArrayList if you've only added one String to it. A list with one element is already sorted. If you want to sort the ArrayList, you should call add() on the ArrayList with each String you need to add, then sort.
You want to sort the characters within the String which is completely different and you need to re-organize the characters, a possible solution (especially knowing that Strings are immutable) is the following Sort a single String in Java
I am stuck in a problem where i have to allocate string objects in an array of strings But the problem is i don't know how many string objects i will be putting in this array.
CODE
static String[] decipheredMessage;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage[pointer] = new String();
decipheredMessage[pointer++] = word;
return true;
What i have done here is i have declared an array of strings and since i don't know how many strings my array is going to contain i dynamically create string objects and assign it to the array.
ERROR
$ java SentenceFormation
arms
Exception in thread "main" java.lang.NullPointerException
at SentenceFormation.makeSentence(SentenceFormation.java:48)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.main(SentenceFormation.java:16)
I don't know why i am getting this problem can anybody help me with this.
Thanks in advance.
Dynamic arrays do not work in Java. You need to use one of the fine examples of the collections framework. Import java.util.ArrayList.
static ArrayList<String> decipheredMessage=new ArrayList<>();;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage.add(new String());
decipheredMessage.add(word);
return true;
You can use a List implementation like ArrayList if you don't know how many elements your array will have.
static List<String> decipheredMessage = new ArrayList<>();
...
decipheredMessage.add("my new string");
Check out the List documentation (linked above) to see what APIs are available.
If you are using Java 5 or 6, you'll need to specify the type in the angled brackets above, i.e. new ArrayList<String>().
Try something like this, and read about List
List<String> decipheredMessage = new ArrayList<String>();
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage. add("string1");
decipheredMessage.add("string2");
return true;
This question already has answers here:
How to convert comma-separated String to List?
(28 answers)
Closed 9 years ago.
I have a comma separated String which i need to convert to ArrayList .
I tried this way
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String CommaSeparated = "item1 , item2 , item3";
ArrayList<String> items = (ArrayList)Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
for(String str : items)
{
System.out.println(str);
}
}
}
Its giving me the Runtime Error as shown
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
at com.tradeking.at.process.streamer.Test.main(Test.java:14)
as i was trying to convert an List to arrayList by force .
The ArrayList returned by Arrays.asList is not java.util.ArrayList. It's java.util.Arrays.ArrayList. So you can't cast it to java.util.ArrayList.
You need to pass the list to the constructor of java.util.ArrayList class:
List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
or, you can simply assign the result:
List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
but mind you, Arrays.asList returns a fixed size list. You cannot add or remove anything into it. If you want to add or remove something, you should use the 1st version.
P.S: You should use List as reference type instead of ArrayList.
You can't just cast objects around like they're candy. Arrays.asList() doesn't return an ArrayList, so you can't cast it (it returns an unmodifiable List).
However you can do new ArrayList(Arrays.asList(...));
Does it absolutely need to be an ArrayList? Typically you want to use the most generic form. If you're ok using a List just try:
List<String> items = Arrays.asList(...);
You can still iterate over it the same way you currently are.
Please try to use bellow code.
String[] temp;
/* delimiter */
String delimiter = ",";
/*
* given string will be split by the argument delimiter provided.
*/
temp = parameter.split(delimiter);
ArrayList<String> list = new ArrayList<String>();
for (int l = 0; l < temp.length; l++)
{
list.add(temp[l]);
}
String CommaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
for(String str : items)
{
System.out.println(str);
}
This question already has answers here:
Looping in ArrayLists with a Method
(3 answers)
Closed 9 years ago.
I have a java program that
reads a text file,
puts all it's words in an ArrayList
puts all the words into an ArrayList, lowercase with punctuation removed
I now want to make two more things.
A function that creates all the anagrams of the strings of a String ArrayList,
an ArrayList of ArrayLists that will store each of the anagrams and the original string into each ArrayList in the ArrayList.
So I want to develop a function that will take a string that I am inserting from one ArrayList into a new ArrayList and make all it's anagrams and put them in an ArrayList and then put that ArrayList in the ArrayList that is reading the old ArrayList.
Something that will look like this:
List<String> arLists = new ArrayList<String>(); //makes new array list
for(String arList : words) //takes values from old array list
ArrayList<String> anaLists = new ArrayList<String>(); //makes a new array list
arLists.add(anag(anaLists,arList,"")); //uses a function that makes an
I want to make a function kinda like this, but what I have made here... doesn't really work.
public void anag(ArrayList<String> anaLists, String s1, String s2){
if(s1.length() == 0){
return anaLists;
}
for(int i = 0 ; i < s1.length() ; i++){ //only runs for string length
String anaList = anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2);
anaLists.add(anaList);
}
}
Some guidance on this would be superb.
To make all anagrams from a string, follow the following steps:
Step 1: Use String's replace to remove whitespace, and make sure all punctuation and capitalization has been removed.
Step 2: Write this function f(string s, string anagram, ArrayList<String> array) and call it with s = yourstring, anagram = "", array = new ArrayList<String>():
If s is empty, add anagram to array and return
For each letter l in s:
newanagram = anagram + l
news = s with l taken out of it (e.g. make a substring of everything before l in s and everything after l in s, and concatenate them together)
call f(news, anagram, array)
This will explore a 'tree' of recursive self calls, and at each 'leaf' of the 'tree' each possible permutation of all the letters will be added to the array. When it finishes, n*n-1*n-2*n-3... aka n factorial entries will be in the array, which is how you know you're on the right track :)
And if you need an anagram of every string in an arraylist, just call it in a for loop.
After some struggle, I have tried to understand your question and here's my answer. Correct me if I am wrong. First of all, you can do all that pre-processing stuff like changing case, removing grammar using one array list. Now to the actual function:
public void getAnag(String baseStr, ArrayList<String> finalAnagList)
{
ArrayList<String> anagList = new ArrayList<String>();
anagList = getAnagrams(baseStr); // getAnagrams is a support function to get the anagrams
anagList.add(baseStr); // I suppose you want to add the base string also to the anagrams list
finalAnagList.add(anagList);
}
And your calling function in program would be:
public void testAnagrams()
{
ArrayList<String> words = getWordsFromFile("/home/list.txt"); // gets the words from the file
ArrayList<String> anagramsList = new ArrayList<String>();
foreach(String word : words)
{
getAnag(word, anagramsList);
}
}
I'm looking to split a List of Strings up as i iterate throught the list imagine the following as the List.
["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"]
So i want to iterate through the list pull out each string ("StringA.StringB.StringC")
Then want to seperate by the "." and assign StringA to a String variable - String B to one and String C. Perform some work and move on to the next.
Any ideas how i can do this?
This is a fairly simple task. Just use a foreach to iterate through the list, and then split the string on the . character.
for(String s: list) {
String[] splitString = s.Split("\\.");
// do work on the 3 items in splitString
}
The variable splitString will have a length of 3.
Of course! You just want String#split().
for (String s : myList)
{
String[] tokens = s.split("\\.");
// now, do something with tokens
}
You need to escape the period in the argument to split() because the string is interpreted as a regex pattern, and an unescaped period (".") will match any character - not what you want!
So you have a list of String[] which are concatenated strings. Unless this is some sort of legacy data structure, you might do better to make this more uniform in some way.
In any case, iteration is pretty straightforward -
List<String[]> l = ....
for (String[] outer: l) {
for (String s: outer){
for (String inner: s.split("\\.")) // s.split takes a regex and returns a String[],
// inner has your inner values now
To iterate through a list, see http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To split a string, use String.split(regex).
The String class has the split(String regex) method, which splits the string by regular expression. If you don't want the hassle of dealing with regular expressions, you can use the very handy StringUtils class from Apache Commons Lang.
List<String> strings=new ArrayList<String>();
for (String s:stringList){
strings.addAll(Arrays.asList(s.split("\\.")));
}
then you'll have all the strings in one list and you can iterate over them.