Java- Add each word to an arraylist? - java

this may be pretty simple, but for some reason I am blanking right now.
Suppose I had a string "Hello I Like Sports"
How would I add each word to an arraylist (so each word is in an index in the arraylist)?
Thanks in advance!

ArrayList<String> wordArrayList = new ArrayList<String>();
for(String word : "Hello I like Sports".split(" ")) {
wordArrayList.add(word);
}

The first thing to do is to split that sentence up into pieces. The way to do that is to use String.split That will return an Array of Strings.
Since you want it in an ArrayList, the next thing you have to do is loop through every String in the array and add it to an ArrayList

String[] words = sentence.split(" ");
list.addAll(Arrays.asList(words));

Try this:
public static void main(String[] args) {
String stri="Hello I Like Sports";
String strar[]=stri.split(" ");
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(strar));
for(int x=0;x<arr.size();x++){
System.out.println("Data :"+arr.get(x));
}
}
Output :
Data :Hello
Data :I
Data :Like
Data :Sports

you can use the split method of the String and split on spaces to get each word in a String array. You can then use that array to create an arrayList
String sentence ="Hello I Like Sports";
String [] words = sentence.split(" ");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(words));
String.split()
Arrays.asList()

A little search would have done the work.
Still I am giving a solution to this. You can use Split.
You can later add those array elements to arraylist if you require.
String s="Hello I like Sports";
String[] words = s.split(" "); //getting into array
//adding array elements to arraylist using enhanced for loop
List<String> wordList=new ArrayList();
for(String str:words)
{
wordList.add(str);
}

First, you have to split the string, and :
if you want a List, use Arrays.asList
if you want an ArrayList, create one from this List.
Sample code :
final String str = "Hello I Like Sports";
// Create a List
final List<String> list = Arrays.asList(str.split(" "));
// Create an ArrayList
final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(str.split(" ")));
Using Arrays.asList and the ArrayList constructor avoids you to iterate on each element of the list manually.

try this code was perfect work for get all word from .txt file
reader = new BufferedReader(
new InputStreamReader(getAssets().open("inputNews.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
for(String word :mLine.split(" ")) {
lst.add(word);
}
}

Related

How to add items back to an ArrayList after appending to StringBuilder?

ArrayList<String> itemslist = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (String item : itemslist) {
stringBuilder.append(item);
stringBuilder.append("\n");
}
String textArray = stringBuilder.toString();
What is the way to create an ArrayList from textArray again? Because I add the textArray to SQLite since SQLite does not accept an Array, but in this way I can add the items to database, but don't know how to make an array again when I retrieve them from SQLite.
If you want to split the String at the line breaks, you can try this:
String[] arraySplit = textArray.split("\n");
ArrayList<String> newList = new ArrayList<>(Arrays.asList(arraySplit));
Edit
Be aware of the comment from #Robert, since this will split the given String on every line break char.

Splitting by Tabs in Java

I have a file scanned line by line into an ArrayList.
I then create a new ArrayList in which I want to temporarily store that line into so that I may access certain values.
Ex. IDname(tab)IDnumber(tab)vote(tab)date
So, I create the temporary ArrayList named voteSubmission, and I go through every String in the fileRead array.
Why is it that I get the error incompatible type for my split method?
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
voteSubmission = x.split("\t");
}
The split method returns an array, not an ArrayList.
Either work with an array or convert it to an ArrayList manually.
x.split("\t"); this function will return an array not array list
The split function states that:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Returns:
the array of strings computed by splitting this string around matches
of the given regular expression
You may try to change your code like this:
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
for(String value: x.split("\t"))
{
voteSubmission.add(value);
}
}
The output of split() is of type string[] array and you are trying to assign to an ArrayList type, which is incompatible.
Change your code to
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
String arr[] = x.split("\t");
if(arr != null && arr.length > 0)
{
for(String value: arr)
{
voteSubmission.add(value);
}
}
}
The error is: Type mismatch: cannot convert from String[] to ArrayList<String>
Which means that x.split("\t") provides a String[] array, but you assign it to an ArrayList.
If you'd like it to be an ArrayList, you'd have to convert it like this:
new ArrayList<String>(Arrays.asList(x.split("\t")));
But since you are doing this in a loop it is likely that you would like to store all Arrays within the ArrayList. To do this, you have to create an ArrayList of type String[], like this:
ArrayList<String[]> voteSubmission = new ArrayList<String[]>();
for(String x : fileRead){
voteSubmission.add((x.split("\t")));
}

how to store a array of String in Array List. can we use array of an Array List. if yes then how?

is it possible to run the following code with logic in 6th line ?
public class arraylist{
public static void main(String args{}){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible?
}
Iterator it=al1.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
Change al.add(s); by al.addAll(Arrays.asList(s)); and you should be all set.
Try the following:
ArrayList<String> al = new ArrayList<String>(Arrays.asList(s));
You have the answer in your question.
When you say you want to convert array asList
As many have already suggested, use Arrays.asList. But before the code would work, you would still need to fix the formatting as you have code outside the main method that is referring to your array list variable in the main method.
public static void main(String[] args){
String s[]={"Sam","Tom","Jerry"};
ArrayList al=new ArrayList();
al.add(Arrays.asList(s));
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
}
al.add(s);//i want this type of logic so i can add the elements of string once.is it possible ?
Yes. It is possible.You can add any object to ArrayList including array object.
But while iterating the ArrayList object you will get an array element by calling it.next().So output will be String representation of array object not the array elements
So try this
String s[]={"Sam","Tom","Jerry"};
ArrayList<String> al=Arrays.asList(s);
Iterator it=al.iterator();
while(it.hasNext())
{
String element=String.valueOf(it.next());
System.out.print("Element"+element);
}
I did the following to store arrays in a ArrayList. The declaration is:
ArrayList<String[]> training = new ArrayList<String[]>();
To input the words and add it:
String input = sc.nextLine();
s1 = input.split(" ");
training.add(s1);
The split method splits the string with spaces and stores each word in the respective index in array s1 which was already declared with the size required for the program."sc" is the scanner object already declared.The individual arrays can be accessed by using:
String s4[] = training.get(index_of_array_you_want);
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList arr=new ArrayList(Arrays.asList(array))

Buffer string to array list, and split

I am buffering a text file of into 'arraylist lines' i then need to split each line into a new arrayList parts, so that i can find information from each line and add the data to a model i have built, the reason i am using arrayLists is because of there expandable properties, meaning i wont need to worry about the size of either the line or the text file.
the code is below:
try(BufferedReader buffer =
new BufferedReader(new FileReader("src/Sample.txt")))
{
String currentLine;
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> parts = new ArrayList<String>();
//ListIterator<String> lineItr = lines.listIterator();
while((currentLine = buffer.readLine()) != null)
{
lines.add(currentLine);
for(String line : lines)
{
parts.addAll(line.split("\\s+"));
}
//lineItr.next();
//lineItr.set(currentLine);
//System.out.println(lineItr.next());
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
i am having my troubles with parts.addAll(line.split("\s+");
i do not understand why the statement does not iterate through lines, splitting and adding each part of the string to the parts array list, am i misunderstanding something here?
thanks Babble
list.addAll() accepts a java.util.Collection where as str.split returns you an array is not a collection. Hence you can not add it directly to a list. You need to convert into a list first.
for(String line : lines)
{
parts.addAll(Arrays.asList(line.split("\\s+"));
}
String.split() returns Array of String . So you have to use Arrays.asList() to convert it into list .
parts.addAll(line.split("\\s+"));
Above line should be:
parts.addAll(Arrays.asList(line.split("\\s+")));
Or :
Collections.addAll(parts, line.split("\\s+"));
try this
parts.addAll(Arrays.asList(line.split("\\s+")));
List.addAll accepts a Collection but line.split("\\s+") returns String[]. You can do it this way
parts.addAll(Arrays.asList(line.split("\\s+")));
Every time a new line arrives, you append the whole thing all over again. Drop the inner "for" loop, and just split currentLine instead.
EDIT based on comment:
The Java Way would be implementing the year and month objects as containers. The simpler alternative is using string-keyed maps.

Java: deepcopy list entry without instancing a new list

I've got a little problem while doing my programming task. I want to read some lines from a file (no problem so far) and tokenize it. Every line has about 4 tokens and each of them should find a place in a list. In the end, every line should be in a list too.
A little example to clarify this:
File Content:
foo boo barbii buu baa
output:
[[foo, boo, bar], [bii, buu, baa]]
And heres the code I'm dealing with
String fileContent = fileloader(file.toString());
List<String> linesList = new ArrayList<String>();
String[] lines = fileContent.split("\n");
for(String line:lines){
String[] splittedLine = line.split("\t");
for(String words:splittedLine){
linesList.add(words);
}
lexiconContent.add(linesList);
linesList.removeAll(linesList);
}
I guess there's a problem with the references, because the first iteration works well! But in the second iteration, it copies the actual second content also to the first (0) list position and so on.
Finally I got something like [[], [], [], []]
The problem is that, you have created only one list, and adding a reference to that list to your outer list, by modifying it on each iteration. So, the final modification done to that list will be reflected for all the references.
You can solve this problem by creating a new linesList each time in the loop: -
List<String> linesList = null; // Don't initialize here
String[] lines = fileContent.split("\n");
for(String line:lines){
String[] splittedLine = line.split("\t");
linesList = new ArrayList<String>(); // Initialize a new list everytime.
for(String words:splittedLine){
linesList.add(words);
}
lexiconContent.add(linesList);
}
And yes, you can also simplify your for loop to: -
for(String line:lines){
String[] splittedLine = line.split("\t");
lexiconContent.add(new ArrayList<String>(Arrays.asList(splittedLine)));
}
This way, you don't have to iterate over your array, and add individual elements to your List. In fact, you don't need an intermediate list at all.
In your code..Instead of creating new ArrayList for each iteration in loop: for(String line:lines) You are just adding the words (in nested loop) in the old object of ArrayList that you had used right from the first iteration of outer loop and storing that same reference value at all subsequent index of lexiconContent ArrayList.Also at the end of each iteration of outer loop you are clearing the linesList .So Finally you are remained with N number of entries in lexiconContent...Where the Element at each index of lexiconContent is nothing but the reference value of the single object of ArrayList(lineList) which is Empty!!!
You should use following code instead:
String fileContent = fileloader(file.toString());
List<String> linesList = null;
String[] lines = fileContent.split("\n");
for(String line:lines){
List<String> linesList = new ArrayList<String>();
String[] splittedLine = line.split("\t");
for(String words:splittedLine){
linesList.add(words);
}
lexiconContent.add(linesList);
}

Categories

Resources