Splitting by Tabs in Java - 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")));
}

Related

Converting List<List<String>> to array

I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}

Iterating over split string

After looking for a while, it's still bugging me:
I have a simple code where I want to retrieve data looking like:
data1/data2/style…
and I want to separate the data at each /. So I have written:
MyData = data.split("/")
and then:
for (i = 0; i < myData.size; i++)
to iterate over the values. But I'm getting the following error:
no signature of method length for type argument: () values: []
so I'm assuming that myData is empty.
if you want to iterate using an integer, you should use MyData.size() in the for loop.
But it is a better idea to do:
String[] myData = data.split("/");
for (String s: myData) {
System.out.println(s);
}
to use each string of the array.
If the iteration only iterates once over your array, then it may be your string that has a problem. As a double check, you may do:
System.out.println(myData.size());
You may also want to add a breakpoint after the .split() and look using a debugger if the array really contains all the strings you're expecting it to contain.
I am having some trouble understanding your question, even with the translation :)
In the line
mesDonnees = maDonnee.split("/");
mesDonnees needs to be a String array (String[]) and you can loop through it like:
for (String str : mesDonnees) {
//... do somwething with str
}
You can rename str something in French if you like, I couldn't think of a suitable name

java get elements inside array but know arrayname in string

String[] strsub0={"out","err","in","console()"};
String[] strsub1={"print","println","append","close","flush"};
i want to get array elements and i know the name of the array.but i know aray name in String
int i=0; //this i get through a loop ,so i can't code strsub0 in my code.
String arrayname="strsub"+i; //this is array name i want ,but it is a String.
//so i want get all elements inside array which name is strsub+i ;
//arrayname.length not return strsub0.length but i want it.
for(int z=0;z<arrayname.length;z++){
System.out.println(arrayname[z]);
}
You want an array of arrays.
String[][] strsub={{"out","err","in","console()"},
{"print","println","append","close","flush"};
Then you can get
String[] arr = strsub[i];
You could use a Map whose key is what you want and whose value is the array. Like the following:
Map<String, String[]> map = new HashMap<>(); //(assuming you have Java 7+ for the <> operator)
map.put("strsub0 ", new String[]{"out", "err", "in", "console()"});
map.put("strsub1 ", new String[]{"print", "println", "append", "close", "flush"});
Then retrieve the values like: map.get(arrayname)[i]. Of course you would have to check whether map.get(arrayname) actually exists or is null

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))

Java- Add each word to an arraylist?

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);
}
}

Categories

Resources