prog rice bowl prog rice bowl - 7 months ago 20
Java Question

How to interleave lists

I have something in my mind which have been bothering me for quite a while now and hope I can get some kind souls to help... :D

Anyway, here's what I wanna do:

I do actually have a number of list, say

List<String> a = {"for testA1", "for testA2", "for testA3"};
List<String> b; = {"for testB1", "for testB2", "for testB3"};
List<String> c; = {"for testC1", "for testC2", "for testC3"};


And I have an array list of objects that I want to add these strings into, i.e.

List<ObjectA> thislist = new ArrayList<ObjectA>();


In my ObjectA class I have:

public class ObjectA{

String testA;
String testB;
String testC;
}


My final output should be:

List<ObjectA> -



  • testA1

  • testB1

  • testC1

  • testA2

  • testB2

  • testC2

  • testA3

  • testB3

  • testC3



How can I go about setting these Strings in my object from the given individual list?

Sorry for my bad English, I hope it's understandable.

I had this in mind but didn't quite understand.

My code was

List<String> aList = ....;
List<String> bList = ....;
List<String> cList = ....;

List<ObjectA> someList = new ArrayList<ObjectA>();

for(String a: aList){
ObjectA obj = new ObjectA();
obj.setTestA(a);
}

ListIterator litr = someList.listIterator();
while(litr.hasNext()) {
ObjectA element = (ObjectA) litr.next();
// I wanna loop List<String> bList and add element.setTestB but it doesn't work.
// This is what I wanna do...
}

Answer
Iterator<String> aIt = a.iterator();
Iterator<String> bIt = b.iterator();
Iterator<String> cIt = c.iterator();

List<ObjectA> thislist = new ArrayList<ObjectA>();


// assumes all the lists have the same size
while(aIt.hasNext())
{
    Object A o = new ObjectA(aIt.next(), bIt.next(), cIt.next());
    thisList.add(o);
}
Comments