Reading from an ArrayList - java

I am reading from a text file and saving the lines into an ArrayList. But I have had no success in how to go through and read all of the specific characters in the ArrayList, how many columns and rows there are.
This is the code I have written so far:
String line;
BufferedReader br = new BufferedReader(r);
ArrayList<String> myArrayList = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
myArrayList.add(line);
.........
}

If I am reading your post right you are wanting to further break apart your lines (your reference to columns). Since you are storing String objects you will need to further break apart those entries into another List to truly parse through your words and characters appropriately.
Java used to have something called the StringTokenizer which could do what you want but that is now deprecated and replaced by the String.Split() method. By iterating through your ArrayList and splitting the String Object by specific delimiters (such as a space or a period), you should be able to further breakdown your existing ArrayList and create a new List with individual words, or even characters.

I do not know why you use "store.add(line)". You should use myArrayList instead of this.
After you have stored everything in the ArrayList you can use a for-each loop to traverse through the list:
for (String string : myArrayList) {
// do everything with the strings here
}

You aren't calling the List myArrayList, I think you want to change this
ArrayList<String> myArrayList = new ArrayList<String>();
to (using the diamond operator and the interface type) -
List<String> store = new ArrayList<>(); // <-- match the name.
You can count the "rows" by getting the size of the List -
int rows = store.size();
To count "columns" you would need to iterate the List and examine the lines. (or you could do that while you read the input) -
for (String line : store) {
// count columns in line
}

If you want to go through a ArrayList there are many ways that you can try
You can easily get number of elements in the ArrayList using size() method.
e.g.
//traditional way
for(int i = 0; i< arrayList.size(); i++){
System.out.println(arrayList.get(i));
}
//enhanced forloop
if your ArrayList is String type
for(String row : arrayList)
System.out.println(row);
With Java 8 you cane have more easier iterator that can use to go through the ArrayList
Edited
If you wanna read character by character
for(String row : arrayList){
char []letters = row/toCharArray();
for(char character : letters)
System.out.print(character + " ") ;
}

Related

I'm getting a "concurrentModificationException" in java, but I'm not changing the list I'm iterating through

I have an ArrayList<List<String>> that I'm trying to iterate through and print, however, I keep getting a ConcurrentModificationException.
My ArrayList<List<String>> represents lines of text, where each inner list is a line of a book and contains the strings that make up that line. I want to print the book out line by line. Here's the code that's causing the error:
public void print(ArrayList<List<String>> book) {
if (book == null) {
return;
}
for (List<String> lst : book) {
StringBuilder line = new StringBuilder();
for (String s : lst) {
line.append(s + " ");
}
// delete the extra space at the end
line.deleteCharAt(line.length() - 1);
// print out the line
System.out.println(line.toString());
}
// print out an extra newline to get ready for next input
System.out.println();
}
Note: This print function takes as input the book, which is the output of another function. This other function is only used to parse the text file and put the words in the ArrayList<List<String>> format.
A concurrent modification exception is raised when a list modification is done while at the same time iterating through the list.
Above you are just iterating through the list, but at the same time elsewhere someone alters the list.
Maybe a CopyOnWriteArrayList might be interesting. But several solutions are imaginable depending on your code.
Here is your error :
you cannot edit a reference holds by an arraylist inside your for loop
String s = line;
// delete the extra space at the end
s.deleteCharAt(s.length() - 1);
Line is a string from your lst and Since strings are immutable it would be more suitable to declare a new String

Iterable to ArrayList elements change

So I am implementing a mapreduce job which means I am dealing with key value pairs.
I have the variable
Iterable<FreqDataWritable> values
FreqDataWritable is an object that contains pieces of information, but for now I am only concerned with one piece of information it holds which is a String which is accessed by getFilename().
I have the following loop:
ArrayList<String> filenames = new ArrayList<String>();
for(FreqDataWritable i : values) {
filenames.add(i.getFilename());
}
Now all I want to do is print the values in the array list filenames.
for(int i = 0; i < filenames.size(); i++) {
System.out.println(filenames.get(i));
}
However when I do this everything in filenames is the same. The only thing printed out is a single filename printed multiple times.
My original code is more complex than this, but I simplified it for help. Anyone know how to fix this?
Thanks
I figured it out. Hadoop has an odd memory usage so when I iterated over the values the first time it was just adding the same object over and over again to the arraylist.
Instead I need to do this:
for(FreqDataWritable i : values) {
filenames.add(new String(i.getFilename()));
}
for(String filename : filenames) {
System.out.println(fn);
}
Let me know if this will help?
Have you tried an iterator-based method?
Iterator i = values.iterator();
fileNames.add(i.next().getFileName());
for(i; i.hasNext();) {
String stringI = i.next().getLast().getFileName();
if(!stringI.equals(fileNames.get(fileNames.size() - 1)))
fileNames.add(i.next().getLast().getFileName());
}

How do I make an ArrayList of ArrayLists from an ArrayList by using a function that makes ArrayLists in an ArrayList from Strings of an ArrayList [duplicate]

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

split string with comma operator into arrraylist

I have a string
String strNumbers = "One,Two,Three,Four,Five";
O want to split this string and produce
One
Two
Three
Four
Five
Help me out please.
I am using following code
String strNumbers = "One,Two,Three,Four,Five";
//split the string using split method of String class
String[] numbers = strNumbers.split(",");
//create new ArrayList object
ArrayList<String> aListNumbers = new ArrayList<String>();
//add individual numbers to the ArrayLists
for(int i=0; i< numbers.length; i++){
aListNumbers.add(numbers[i]);
}
List<String> aListNumbers = new ArrayList<String>(
Arrays.asList(strNumbers.split(","));
split gives you an array. Arrays.asList wraps a list around an array.
If you really need an ArrayList, you can then use its ArrayList(Collection) copy constructor.
Right now you're just printing out the ArrayList object. You need to iterate through the ArrayList and print out the String values it contains. You can do this with System.out.println, which will automatically put a new line after each value it prints.
for (String number : aListNumbers) {
System.out.println(number);
}

Removing [] from ArrayList Output and Storing in HashMap<String,Object>

I have a HashMap. The key will be a string and value can be anything ranging from a variable to a ArrayList.
The problem is I have an ArrayList. The values stored in the ArrayList are Region1,Region2,Region3,Region4.
So when I put this ArrayList in HashMap and print the HashMap I get the output as
[Region1,Region2,Region3,Region4].
Problem is I need to insert this whole comma separated String in Db and my procedure cannot recognize [] in this output.
How can I solve it..I cannot change anything at DB end.
Here's the code snippet:-
ArrayList<String> Region=new ArrayList<String>();
Region.add("Region1");
Region.add("Region2");
Region.add("Region3");
System.out.println(Region);
Output is [Region1, Region2, Region3]
I put this ArrayList in HashMap
HashMap<String,Object> regionHashMap=new HashMap<String,Object>();
regionHashMap.put("regionssss", Region);
System.out.println(regionHashMap);
Output is {regionssss=[Region1, Region2, Region3]}.
How can i Remove [] from the ArrayList...
I already succedded by using StringBuffer and Iterator but I cannot use it everytime Since I have huge number of ArrayList which will go inside the HashMap..
The String representation of a List automatically encloses with "[ ]" characters.
You could either create your own 'toString' method:
private String listToString(List<?> l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l.size(); i++) {
sb.append(l.get(i));
if (i != l.size() -1) sb.append(", ");
}
return sb.toString();
}
Or, you could use the substring function to remove the braces:
String s = list.toString();
s = s.substring(1, s.length()-1);
Don't use toString() at all. It is not meant to be used to create formatted UI strings. It is a developer tool, not a user presentation tool.
To do what you want is to just create a method to do your display and do the formatting in that method instead.
see this post to get more on this.
Try subclassing HashMap and override the toString() method

Categories