Split Arraylist of 2 types when printing it

ddraz Source

I have a list composed of Objects Every object is comprised of 2 different values

int number;

String name;

ArrayList<Object> objectList= new ArrayList<Object>();

I have another list composed of Cars Every Car has one value

String type;

ArrayList<Cars> carList= new ArrayList<Cars>();

I want to print half the objectList first then the carList then the other half of the objectList

Like so.. for example:

Output= "number + type + name"

Basically i want the second list to be printed in between the first list.I searched the web but i am not really sure what i should be looking for and how exactly to code this.

Again i am sorry for the bad question.. i am trying to learn coding by myself because i can't afford it.

Thanks in advance.

javaarraylist

Answers

answered 7 days ago Roberto Rodriguez #1

Just iterate through the first list, and use the index to access the corresponding Object in the second list:

for(int i = 0; i < objectList.size(); i++){
   Object obj = objectList.get(i); 
   Car car    = carList.get(i);

  //Print Here
}

answered 7 days ago Mạnh Quyết Nguyễn #2

You say you want to print half of your list first, then you are able to split the original list by half:

Streams.of(objectList.sublist(0, length/2), 
           carList, 
           objectList.sublist(length/2, length))
.flatMap(Collection::stream)
.forEach(o -> {
    if (o instanceof YourObject) {
       YourObject o1 = (YourObject)o;
       // Print with YourObject
    } else if (o instanceof Cars) {
       // Print car objects
    }
})

answered 7 days ago coder3101 #3

You can very easily achieve this by a for loop. But as per your output format

The size of the objectList and carList must be same for this to work.

Try something like this :

for(int i=0;i<objectList.size();i++){
    String name; int number;
    number = objectList.get(i).number;
    name = objectList.get(i).name;
    String type = carList.get(i).type;
    System.out.Println(name+type+number);
}

As per your comment, if carList is in another class and is private then, you need to set a getter method that takes an index and returns the type Like this :

public class A{
  private ArrayList<Car> carList = new ArrayList();
........ //some codes
  public String getTypeAtIndex(int i){ return carList.get(i).type;  }
    }

Then anywhere you can call

A a;
String type = a.getTypeAtIndex(i);

comments powered by Disqus