Java ArrayList concept - java

How do you loop through an ArrayList within an ArrayList?
For example, If I have an ArrayList called plants of Plant objects. And each Plant object has a random number of flowerNames inside. How do I go through the ArrayList, stop at each Plant and print out the Plant's list of flowerNames? (just an example) and then move on to the next Plant, etc.
Plant: has an ArrayList of Flowers: has an ArrayList of flowerNames
Plant is in one class, Flowers is in another class
Is there a way to do this with the standard for loop? Not interate...?

Try something like this .
for( Plant plant : plants) {
for(Flowers flower : plant.getFlowers()) {
System.out.println(flower.getName());
}
}

ArrayList<Object> outerList = new ArrayList<Object>();
ArrayList<Object> innerList = new ArrayList<Object>();
for(Object outer: outerList){
for(Object inner: innerList){
//Perform operation with innerList. Print or something else.
}
}

if you are not sure at which position you will get another list object use instance of method and check. Sample code is here.
for(int i=0;i<l1.size();i++){
if(!(l1.get(i) instanceof List<?>)){
System.out.println(l1.get(i));
}
else {
for(int j=0;j<((List)l1.get(i)).size();j++){
System.out.println(((List)l1.get(i)).get(j));
}
}
}

Related

Deleting specific object from ArrayList using for-loop

I am trying to delete one object from an ArrayList, but after iterating through the list with the for loop i'm stuck at what to do next. nameInput is a lowercase string from the user.
If i run this it prints the object from arr list equal to the input from nameInput. But I cannot understand how to go from printing that object to deleting it?
I'm sure this is a stupid question but the 50+ answers i have read and tried all seem to fail me (or more likely I fail to understand them). I have tried the list.remove and removeIf.
private ArrayList<Arr> arr = new ArrayList<>();
private void removeItem() {
for (Object arr : arr) {
if (((Arr) arr).getName().equals(nameInput())) {
System.out.println(arr);
break;
} else {
System.out.println("Error");
}
}
}
Using for loop
List<Arr> arr = new ArrayList<>();
for (Arr item : arr) {
if (item.getName().equals(nameInput())) {
arr.remove(item);
break;
}
}
If not call break after remove element, you get ConcurrentElementException
Note from #Aomine: you have to implement correct Arr.equals() method.
Using Iterator
List<Arr> arr = new ArrayList<>();
Iterator<Arr> it = arr.iterator();
while (it.hasNext()) {
Arr items = it.next();
if (item.getName().equals(nameInput())) {
it.remove();
break; // you can continue iterating and remove another item
}
}
Using Streams
List<Arr> arr = new ArrayList<>();
arr.removeIf(item -> item.getName().equals(nameInput()));
Remove all items that match given condition
This is not good to remove element from ArrayList. In case you know that you have to remove element from the middle of the List, do use LinkedList.
You are trying to remove an item while you are traversing/iterating the list in the for loop. You cannot remove an item from the list iterating it in a for loop. Use an Iterator instead and invoke arr.remove().
If you use Java 8 you could do
private void removeItem() {
arr.removeIf(t -> t.getName().equals(nameInput));
}
Note that this will remove all objects with name equal to nameInput
Also you should change your declaration of arr to
List<Arr> arr = new ArrayList<>();
A couple of things here...
The loop variable receiver type should ideally be Arr instead of Object as the list contains Arr objects. This also means you no longer need the cast you're performing.
You could remove the item via remove(Object o) but this requires overriding equals and hashcode based on name only. Another option is via an iterator but this would mean changing your code completely. Thus, to keep it as close to your code as possible you can use a for loop; get the index which the object is located and then remove.
Thus, you can do:
for(int i = 0; i < arr.size(); i++){
if (arr.get(i).getName().equals(nameInput)) {
Arr obj = arr.remove(i); // remove the item by index
System.out.println(obj); // print the object
break; // terminate the loop iteration
}
}

How do you add elements from one ArrayList to another?

So I have one ArrayList of fruits which has the name of the fruit and what its predominant vitamin is:
ArrayList<Foods> fruit;
public Fruit() {
fruit = new ArrayList<Foods>();
fruit.add(new Foods("Orange", "Vitamin C"));
}
etc..
I want to add all the fruits with vitamin C to another array list so I iterated over them using:
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
if (vitC.next().contains("Vitamin C")) {
vitCfruit.add(vitC.next());
}
}
However this adds the next value, so if apple was after orange in the list it would add apple to the next ArrayList instead of orange.
I'll ignore the apparent error in the code. In order to work with the element on the list you should do the following:
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
Foods x = vitC.next();
if (x.contains("Vitamin C")) { // should look for a Foods object here!!!
administrators.add(x);
}
}
the vitC.next() in the 'if' you declared will work, but you will not be accessing the same element in the next line when add it to the new list.
use a tmp variable to store the vitC.next() and in case it match the condition you can still add ot..
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
tmp = vitC.next();
if (tmp.contains("Vitamin C")) { // should look for a Foods object here!!!
administrators.add(tmp);
}
}
The enhanced for loop makes this straightforward:
for (Fruit thisFruit : fruit) {
if (thisFruit.contains("Vitamin C")) {
vitCfruit.add(thisFruit);
}
}
In Java 8, this is simple with lambdas:
List<Foods> vitCfruit = fruit.stream()
.filter(f -> f.contains("Vitamin C"))
.collect(Collectors.toList());

How to display java bean objects in a container without using get() in a loop?

I'm new to java. can you guide me on the below snippet. I have added 5 EmpBean objects to the ArrayList arr.
List arr=new ArrayList();
for(int i=0;i<5;i++)
{
EmpBean eb=new EmpBean();
eb.setFirstID(i);
eb.setLastID(i);
arr.add(eb);
}
How do I display those 5 EmpBean objects in a single shot and not by using arr.get(0) and display individual EmpBean objects?
please help,
Thanks
You can iterate through your list with a for loop.
for (EmpBean empBean : arr)
{
//do stuff with your empBean instance
}
or
for (int i = 0; i < arr.size(); i++)
{
EmpBean empBean = arr.get(i);
// do stuff with you empBean
}
You need to loop over your ArrayList in order to print its value:
Example
for (EmpBean bean: arr) {
System.out.println(bean.toString());
}
To override toString method in your class, you can do something like this:
#Override
public String toString() {
return String.format("First id : %s, Second Id : %s", getFirstID(), getSecondID());//suppose you have a getter's for these variables.
}
To display all object in single shot just print the arr object
System.out.println(arr)
Because List already override toString() method to display all it's elements in angular brackets [elements.]
To display each element use foreach loop.
come on guys for loop is soo java7, let's be up-to-date :D
arr.stream().forEach(a -> System.out.println(a));
redefine toString in EmpBean to whatever you want to display :)
If it's a primitive type List then you can get all the elements when you print the list itself, but incase of List<Object> you won't able to display the contents like that.
In that case you have to use either a loop or an iterator:
1.
List<EmpBean>list = new ArrayList<EmpBean>();
for (EmpBean ob:list) {
//do stuff with o
}
2 .
List<EmpBean>list = new ArrayList<EmpBean>(); //you need to populate this list
Iterator iter = list.iterator();
while (iter.hasNext()) {
Object o = iter.next();
//do stuff with o
}

how to set ArrayList from another ArrayList which has elements as Arraylist

iam unable to add to ArrayList which is an atrribute in Form . from ArrayList which has elements as ArrayList.
I have to do the above, to iterate the ArrayList , to display in jsp.
Edit : below is the code in DAO where iam adding ArrayList in to ArrayList
while( rs.next())
{
if(null!=columnList && columnList.size()>0){
baseColumnList.add(columnList);
}
columnList = new ArrayList();
for(int i=1; i<=rs.getMetaData().getColumnCount(); ){
columnList.add(rs.getString(rs.getMetaData().getColumnLabel(i)));
//child = new ArrayList();
i++;
}
}
In Action class, i have get the each element of parent ArrayList, which is again an ArrayList. add it to form ArrayList
I don't exactly know what you mean but, if I understand correctly, I think you want to loop over an ArrayList<ArrayList<Object>>?
In that case, you can just loop over each ArrayList:
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>()
..
for (ArrayList<Object> l1 : listOfLists) {
for (Object something : l1) {
..
}
}

Issue iterating through ArrayLists

I have two questions. I have an object here that is of type ArrayList, and for this case let's call it "Car".
I have made 2 of them:
Car car1 = new Car();
Car car2 = new Car();
I have a function to add items to those Car objects:
car1.addPart("Front Wheels");
car1.addPart("Rear Wheels");
car1.addPart("Rear View Mirror");
car2.addPart("Rims");
car2.addPart("Steering Wheel");
car2.addPart("Bumper");
I need to have a function called sameContents() that I can call on car1:
car1.sameContents(car2);
which passes in an object of type ArrayList and checks it with car1 to see if they have the same contents and in the same order.
public boolean sameContents(Car c) {
ArrayList<String> other_car = c; // error: Type mismatch:
// cannot convert from Car to ArrayList<String>
for (String c : this.parts) {
System.out.println(c);
for(String oc : other_car) {
// stuff
}
}
}
I seem to be having all sorts of issues with this one. I can't get the other_car variable to be used in a foreach loop.
The second one that needs to be done is transferContents.
It's called like:
car1.transferContents(car2);
which transfers the items in car2 into car1 and then leaves car2 empty. I can't seem to get the ArrayList to work again in a foreach loop which is what I think I need.
public void transfer(Car c) {
// code for transfer method.
// this.parts is the arraylist of car parts
for (Car c: c) {
this.parts.add(c);
}
// not sure how to set car2 to empty...
}
Given some List<T> foo, foreach loops, e.g.:
for(T item : foo){
// body
}
are just a shorthand syntax for this idiom:
Iterator<T> iter = foo.iterator();
while(iter.hasNext()){
T item = iter.next();
// body
}
To check that there are more items in the list, you call iter.hasNext(), to retrieve the next item, you call iter.next().
Walking two lists can be done by keeping around 2 iterators, checking that both iterators have more elements, and then retrieving those elements. We can eliminate some boundary conditions on different length lists by realizing that different length lists cannot contain the same elements (since one list has more than the other).
From your description, it sounds like Car contains a property List<String> parts;, so we can formulate a solution as:
// different sizes, can't be equal
if(this.parts.size() != other.parts.size()){
return false;
}
// get iterators
Iterator<String> left = this.parts.iterator();
Iterator<String> right = other.parts.iterator();
// safe to only check `left` because the lists are the same size
while(left.hasNext()){
// check if left part is equal to the right part
if(!left.next().equals(right.next())){
// values are different, know at this
// point they're not equal
return false;
}
}
// at this point, have exactly the same values
// in the same order.
return true;
As for your transferContents method, you have the right idea, but you cannot iterate over the Car, you need to iterate over the List<String> parts. To remove individual parts, you can use remove() method, called like the add method, or to remove all elements, you can call clear()
Putting this together:
for (String part : c.parts) {
this.parts.add(part);
}
c.parts.clear();
You can rely on the java api to do all that you need.
The ArrayList equals method checks for order while comparing two lists.
You can use the removeAll() and addAll() methods to transfer contents.
public class Car {
private final List<String> parts = new ArrayList<String>();
public void addPart(String p) {
parts.add(p);
}
public boolean sameContents(Car c) {
return this.parts.equals(c.parts);
}
public void transfer(Car c) {
final List<String> temp = new ArrayList<String>(c.parts);
temp.removeAll(this.parts);
this.parts.addAll(temp);
c.parts.clear();
}
}
Your car should not be an array list, but have one. E.g. something like this:
class Car {
ArrayList<String> parts;
// ...
}
Then your sameContents method can simply call the lists's .equals() method to do the comparison:
public boolean sameParts(Car other) {
return this.parts.equals(other.parts);
}
Similarly, for transferring parts from another car, use the methods of the Lists to add the parts to your list, and then clear the other list.

Categories