How to populate an array list in a while loop - java

My problem is this
Scanner sf = new Scanner(f);
ArrayList<String> teamArr = new ArrayList<String>();
int counterPopulate = 0;
while(sf.hasNextLine()){
teamArr[counterPopulate] = sf.nextLine();
counterPopulate++;
}
Any solutions, this is surrounded by a try catch.
Getting the problem at this part teamArr[counterPopulate] = sf.nextLine();

Because ArrayList is different than normal arrays, you need to use methods of the ArrayList class to populate the ArrayList.
In your case you need to do:
while(sf.hasNextLine()){
teamArr.add(sf.nextLine());
}
Assuming you're using Java.
Have a look at http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

As you are using ArrayList<String>, add(String value) method is used to add new String Object into the ArrayList.
A simple solution of your problem is given below.
assuming that language is JAVA.
Scanner sf = new Scanner(f);
ArrayList<String> teamArr = new ArrayList<String>();
while( sf.hasNextLine() ) {
teamArr.add(sf.nextLine());
}
for more details about ArrayList and Collection please refer :
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

Related

comparing 2 ArrayList in Java

I got 2 ArrayList
List fileArray = new ArrayList();
List fileTxt = new ArrayList();
List<String> newDoc = new ArrayList<String>();
while((fileName = fileRead.readLine()) !=null){
fileArray.add(fileName);
}
fileRead.close();
while((txtName = txtRead.readLine()) !=null){
fileTxt.add(txtName);
}
txtRead.close();
I want to compare fileArray data with fileTxt data, but don't know how to do that, because to I'm thinking to compare I need to get the data first. And to do that I need to looping the array and using the .get like
for(int a=0;a<fileTxt.size();a++){
System.out.println(fileTxt.get(a));
}
I know this is wrong, but anyone can help me.
note: I want to use something like contains method but can't because the data is 5 million rows. (not equals method)
Updated: I want to find a word in fileTxt that appeared in the fileArray. (so basically its like contains)
To compare 2 values in your 2 arraylists, you do this:
if(fileArray.get(index).equals(fileTxt.get(index)))
There is a wondefull function.
System.out.println(array1.equals(array2));
Then, you might want to check your answer by hands:
ArrayList like1 = new ArrayList();
ArrayList like2 = new ArrayList();
...
boolean flag = true;
if (!Math.min(like1.size(), like2.size()) == Math.max(like1.size(), like2.size()))
{
flag = false;
}
for (int i = 0; i < Math.min(like1.size(), like2.size()); i++) {
if (!like1.get(i).equals(like2.get(i))) {
flag = false;
break;
}
}
You can do this using the removeAll() method.
fileArray.removeAll(fileTxt);
fileTxt.removeAll(fileArray);
If one of them still have data, this means that the two List where different.
But storing 5 millions data in a Java list is not something I will advise you. Perhaps you should think about something else.

Iterator seems to be losing data java

I've got a method that returns a list of hashmaps (the data comes from a ResultSet).
While trying to use an iterator to loop through the data and convert it to a String array, I was finding that the code was not working - It seemed to be losing half of my array data while doing the loop.
When swapping it to use a for loop rather than an iterator, the data was not lost. I tried using both an Iterator() and ListIterator() to no avail
Here is my original code (that wasn't working):
public String[][] getLayoutEdges() throws SQLException {
ArrayList<String[]> returnArray = new ArrayList<>();
List<HashMap> layoutEdges = db.getLayoutEdgesFromDatabase();
ListIterator<HashMap> edgesIterator = layoutEdges.listIterator();
while(edgesIterator.hasNext()) {
ArrayList<String> tmpList = new ArrayList<>();
tmpList.add(edgesIterator.next().get("fromnode").toString());
tmpList.add(edgesIterator.next().get("tonode").toString());
tmpList.add(edgesIterator.next().get("distance").toString());
String[] tmpStr = new String[tmpList.size()];
returnArray.add(tmpList.toArray(tmpStr));
}
String[][] rtn = new String[returnArray.size()][returnArray.size()];
return returnArray.toArray(rtn);
}
Here is the code that does work:
public String[][] getLayoutEdges() throws SQLException {
ArrayList<String[]> returnArray = new ArrayList<>();
List<HashMap> layoutEdges = db.getLayoutEdgesFromDatabase();
for(HashMap tmp : layoutEdges) {
ArrayList<String> tmpList = new ArrayList<>();
tmpList.add(tmp.get("fromnode").toString());
tmpList.add(tmp.get("tonode").toString());
tmpList.add(tmp.get("distance").toString());
String[] tmpStr = new String[tmpList.size()];
returnArray.add(tmpList.toArray(tmpStr));
}
String[][] rtn = new String[returnArray.size()][returnArray.size()];
return returnArray.toArray(rtn);
}
Can anybody tell me why the iterator wasn't working? I'm okay with using a for loop, i just can't for the life of me work out why the original iterator code I wrote wasn't keeping all my data. Wondering if there's a step i'm missing or whether I was trying to use the wrong solution.
You're calling edgesIterator.next() three times for each iteration of the loop in your first snippet, which I'm pretty sure you don't want to do. Just don't do that:
while (edgesIterator.hasNext()) {
HashMap tmp = edgesIterator.next();
tmpList.add(tmp.get("fromnode").toString());
tmpList.add(tmp.get("tonode").toString());
tmpList.add(tmp.get("distance").toString());
String[] tmpStr = new String[tmpList.size()];
returnArray.add(tmpList.toArray(tmpStr));
}
As an aside, if you could avoid using raw types in your API, it would generally be cleaner - I'm talking about the use of HashMap here.
I would also generally favour the second version of your code anyway - unless you need to use the iterator explicitly for some reason, let the syntactic sugar of the enhanced for loop do it for you automatically.
Because of these lines :
tmpList.add(edgesIterator.next().get("fromnode").toString());
tmpList.add(edgesIterator.next().get("tonode").toString());
tmpList.add(edgesIterator.next().get("distance").toString());
The moment you are calling edgesIterator.next() its moving the cursor to the next element.

TreeMap using a string key and an arraylist

I am brand new to using collections, so I am confused on how to do this. I am trying to use a TreeMap to hold a word as the key and then an ArrayList to hold one or more definitions for the word.
public class Dict {
Map<String, ArrayList<String>> dic = new TreeMap<String, ArrayList<String>>();
public void AddCmd(String word, String def) {
System.out.println("Add Cmd " + word);
if(dic.get(word)==null){
dic.put(word, new ArrayList.add(def));
}
}
}
I am getting an error on "new ArrayList.add(def)". I thought this was the correct way to do this, but I am obviously wrong. Does anyone have any ideas as to what I am doing wrong?
Calling ArrayList#add returns a boolean which is not the desired value for your Map, thus getting the compiler error.
You need to insert the ArrayList and then add the element. Your code should look like this:
ArrayList<String> definitions = dic.get(word);
if (definitions == null) {
definitions = new ArrayList<String>();
dic.put(word, definitions);
}
definitions.add(def);
dic.put(word, new ArrayList.add(def)); is the culprit.
since you have declared map to take Arraylist of string as a value. the value to pass for map must be Arraylist of string.
but this line is adding a value as new ArrayList.add(def) since you are trying to create a list and adding element , add method returns boolean -> true if it can add false if it fails.
so it means value to the map is going as a boolean not as arraylist which is against the map declaration.
so use code as below
ArrayList<String> listOfString = dic.get(word);
if (listOfString == null) {
listOfString = new ArrayList<String>();
listOfString .add(def);
}
dic.put(word, listOfString );
You have to break it up, because add does not return the original ArrayList:
ArrayList<String>> NewList = new ArrayList<String>();
NewList.add(def);
dic.put(word, NewList);
You are not actually creating a new ArrayList. Try this:
ArrayList<String> newDef = new ArrayList<String();
newDef.add(def);
dic.put(word, newDef);

Regarding arrayList

I have used scanner instead of string tokenizer ,, below is the piece of code...
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
while (scanner.hasNext()) {
// System.out.println(scanner.next());
String phoneDtls = scanner.next();
// System.out.println(phoneDtls);
ArrayList<String> phoneTypeList = new ArrayList<String>();
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
Iterator itr=phoneTypeList.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
The ouput I get upon executing this...
Home
Cell
Work
As it is seen from the above code is that in the array list phoneTypeList we are finally storing the values..but the logic of finding out the value on the basisi of ',' is not that much great..that is ..
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
could you please advise me with some other alternative ..!! to achieve the same thing...!!thanks a lot in advance..!!
Well, since you asked if there is another way to do it then here is an alternative: You can split the string directly and do it with less code with the foreach statement:
String input = "Home,1;Cell,2;Work,3";
String[] splitInput = input.split(";");
for (String s : splitInput ) {
System.out.println(s.split(",")[0]);
}
No need to use the ArrayList<T> since you can iterate over an array as well.
could you try to split based on ',' STIRNG_VALUE.split(','); will return u an array with strings separated with , may be this helps
If i understand correctly. The problem statement is you want to maintain a list of Phone-Type-List. Like this: ["Home", "Cell", "Work"].
I suggest you keep this in a property file / config file / database which ever makes sense and load it to memory on start of you app.
If the input cannot be changed then as for the algorithm i couldn't think of a better one. Looks good.
You could use split function of string if that makes sense.
First use split on ";"
Then a split on ","
declare the arraylist outside the while loop.
try this, i have made some change for better performance too. hope you can compare and understand the change.
ArrayList<String> phoneTypeList = new ArrayList<String>();
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
String phoneDtls = null;
String value = null;
while (scanner.hasNext()) {
phoneDtls = scanner.next();
if (phoneDtls.indexOf(',') != -1) {
value = phoneDtls.split(",")[0];
phoneTypeList.add(value);
}
}
Iterator itr = phoneTypeList.iterator();
while (itr.hasNext())
System.out.println(itr.next());
I have executed n got the result, check screenshot.

Adding to an ArrayList Java

I am a beginner to java, and need some help.
I am trying to convert an Abstract Data type Foo which is an associated list to an Arraylist of the strings B. How do you loop through the list and add each string to the array.
I may be over thinking it, but I am lost now.
Thanks for the help in advance.
Instantiate a new ArrayList:
List<String> myList = new ArrayList<String>();
Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):
myList.add(yourElement);
If you have an arraylist of String called 'foo', you can easily append (add) it to another ArrayList, 'list', using the following method:
ArrayList<String> list = new ArrayList<String>();
list.addAll(foo);
that way you don't even need to loop through anything.
You should be able to do something like:
ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
list.add(s);
}
Array list can be implemented by the following code:
Arraylist<String> list = new ArrayList<String>();
list.add(value1);
list.add(value2);
list.add(value3);
list.add(value4);
Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)
Recommended reading.
Lists in the Java Tutorial
thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D
import java.util.*;
public class HelloWorld {
public static void main(String[] Args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);
int First = list.get(1);
int Second = list.get(2);
if (First < Second) {
System.out.println("One or more of your items have been restocked. The current stock is: " + First);
Random rn = new Random();
int answer = rn.nextInt(99) + 1;
System.out.println("You are buying " + answer + " New stock");
First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}
}
}
If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add method.
List<String> list = List.of("first", "second", "third");

Categories