Adding to an ArrayList Java - 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");

Related

Restart ArrayList within For-Loop

I'll keep this simple:
I have an ArrayList of names, I have to remove certain words that contain a specific letter, but I am having trouble restarting the for-loop. This is what I got:
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println("Start of List: " + wordList + "\n");
System.out.println("\nDrop: \"a\"");
someRandomFunction(wordList, "a");
System.out.println("wordList is now: " + wordList);
}
public static List<String> removeIfContains(List<String> strList, String removeIf){
List<String> tempList = new ArrayList<>(strList); // creating a copy
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(removeIf))
tempList.remove(i);
}
//Return will not work because of incompatible types.
}
An example of what the compiled code should be:
ArrayList [ Hello, Everyone, I'm, Am, Struggling, In, Computer, Science]
Remove words that start with "A":
New ArrayList [Hello, Everyone, I'm, Struggling, In, Computer, Science]
Remove words that start with "I":
New ArrayList [Hello, Everyone, Am, Struggling, Computer, Science]
The problem with my code is that it won't return the wordlist to how it was before as it begins to read the new word it needs to drop.
If you just want to remove each element in an ArrayList that starts with a certain letter you can utilize the removeIf() method which:
Removes all of the elements of this collection that satisfy the given predicate.
wrodList.removeIf(e -> e.contains(thisLetter));
(Java 8+ required)
It sounds like you want the list to reset after each time you remove elements. To do this you can create a copy ArrayList to check against, and then after each time, set it back to the original:
List<String> copy = new ArrayList<>(wordList); //Creates a copy of wordList
I believe this is what you are looking for. I'm not sure if you want a an instance or static method. I believe your issue is that you are not creating a copy. I noted where I was creating a copy. Good luck in CS.. we've all struggled at one point.
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println(removeIfContains(arrList, "H")); // calling the function and passing the list and what
System.out.println(removeIfContains(arrList, "I")); // I want to remove from the list
}
public static List<String> removeIfContains(List<String> strList, String removeIf){
List<String> tempList = new ArrayList<>(strList); // creating a copy
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(removeIf))
tempList.remove(i);
}
return tempList; // returning the copy
}

how to get value from 2d arraylist

i have arraylists named sub and main,
ArrayList main = new ArrayList();
ArrayList sub=new ArrayList();
i add value to sub and then add sub to main.
example;
sub.add(1);
sub.add(2);
main.add(sub);
now i want to get all values inside sub
so i used following one but .get(j) gives me the error get >> canot find symbol
for (int i=0;i<main.size();i++) {
System.out.println();
for (int j=0;j<sub().size();j++) {
System.out.print(main.get(i).get(j));//error line
}
}
how can i get all values inside subarray of main arraylist
When you declare a variable as
ArrayList main;
This list holds Objects. This means that main.get(i) will only return an Object, even if you add ArrayLists. That's why you get a compiler error: Object doesn't have a method named get().
To fix the problem, you need to use generics:
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub=new ArrayList<>();
Now get() will return a List<Integer> which has a get() method, so the compiler error will disappear.
Generics could be your friend here:
ArrayList<ArrayList<Object>> main = new ArrayList<ArrayList<Object>>(); // or new ArrayList<>(); in Java 7+
ArrayList<Object> sub = new ArrayList<Object>(); // or new ArrayList<>();
If you can't or don't want to use generics, the solution is to cast the expression main.get(i) to an ArrayList first:
System.out.println(((ArrayList) main.get(i)).get(j));
Go through the following code
public class ArrayListDemo {
public static void main(String[] args) {
List<List<Integer>> main = new ArrayList<>();
List<Integer> sub = new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
//If you want to get values in sub array list
for(int i = 0; i < 1; i++){
List<Integer> arr = main.get(i);
for(Integer val : arr) System.out.println(val + "");
}
//If you want to print all values
for(List<Integer> list : main){
for(Integer val : list) System.out.println(val + "");
}
}
}
In the above code, I had declared an ArrayList (main) to keep all Array which are having Integer values. Also i had declared an another ArrayList (sub) to keep all Integer values.
I had used ArrayList data structure because of length of the List will be changing the
run time.
Good Luck !!!

How to add strings into an arraylist between two strings

I am trying to figure out how to add a string, into a string ArrayList, between two strings that are already in. So if I have this
ArrayList<String> List = new ArrayList<String>();
List.add("Yes");
List.add("No");
List.add("Maybe");
How would I go along putting the word "Or" between them and make the ArrayList contain
"Yes" "Or" "No" "Or" "Maybe"?
I have three advices.
First, to name the variables, start with lower-case.
Second, use List as type of variable, instead of ArrayList, you will thank me later, trust me.
Third, to do what you ask for, there is overloaded method add for choosing position :
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add(1,"Maybe"); //insert into position 1 and shift everything to the right.
For this example, if you use System.out.println(list);, you will get this output :
[Yes, Maybe, No]
For adding Or instruction, it would be like this :
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add(1, "Or");
list.add(3, "Or");
System.out.println(list);
Output :
[Yes, Or, No, Or, Maybe]
Also, if you want to make your program more re-usable, you can write a method, that will do this for you for any case of list :
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add("Probably");
list.add("Never");
List<String> orList = addOr(list);
System.out.println(orList);
}
public static List<String> addOr(List<String> list){
List<String> newList = new ArrayList<>();
int count = 0;
for(String text : list){
count++;
newList.add(text);
if (count != list.size()){
newList.add("Or");
}
}
return newList;
}
Having this output :
[Yes, Or, No, Or, Maybe, Or, Probably, Or, Never]
However, if you want to use that list for outputing some message for user, it is not good idea to add "Or", because it is really not part of information. Rather it is good, to create method, which will create output String you desire.
This code
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add("Probably");
list.add("Never");
String niceOutput = addOr(list);
System.out.println("Choose from following options: " + niceOutput);
}
public static String addOr(List<String> list){
String orText = "";
int count = 0;
for(String text : list){
count++;
orText += '\'' + text + '\'';
if (count != list.size()){
orText += " or ";
}
}
return orText;
}
Having this output :
Choose from following options: 'Yes' or 'No' or 'Maybe' or 'Probably' or 'Never'
According to Add object to ArrayList at specified index
List.add(1, "or")
List.add(3, "or")
This should solve your problem.

How to populate an array list in a while loop

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

Naming Arraylists in a loop - Java

I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!
Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);
If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").
Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.

Categories