crm crm - 6 months ago 7
Java Question

How can I combine elements at the same index from separate lists?

I am trying to combine multiple String lists.

Say I have two (could be more) lists of the same size:

List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");


I want to combine the value of the corresponding indexes and place them into a new list:

List3 = new {"1One2One", "1Two2Two", "1Three2Three"};


Currently I have a list of 2 objects, each object contains the list that I want to combine the elements within.

So I want to combine element 1 in the list from object 1 with element 1 from the list from object 2.

This is what I have attempted:

public void generateFileList(List<Object> cl){


int count = 0;
String temp = "";
for(int i = 0; i < cl.size(); i++){

for (int x = 0; x < cl.get(i).getItemList().size(); x++) {
if (count == x){
temp += cl.get(i).getListItem(x);
break;
}

}
count++;
textList.add(temp);

}
}
public void test(){
for(String s : textList){
System.out.println("List Element - " + s);
}
System.out.println(textList.size());
}


Which prints out:

List Element - 1One
List Element - 1One1Three


What am I doing wrong here?

Answer

First, the code you have won't compile. It should be:

List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");

Next, it is best to use an Iterator than access a List by index:

public List<String> concat(final List<String> list1, final List<String> list2) {
    final Iterator<String> i1 = list1.iterator();
    final Iterator<String> i2 = list2.iterator();

    final List<String> combined = new ArrayList<>();
    while (i1.hasNext() && i2.hasNext()) {
        combined.add(i1.next() + i2.next());
    }
    return combined;
}

For an arbitrary number of List:

public List<String> concat(final List<String>... lists) {
    final List<Iterator<String>> it = new LinkedList<>();
    for (List<String> l : lists) {
        it.add(l.iterator());
    }

    final List<String> combined = new ArrayList<>();
    outer:
    while (true) {
        final StringBuilder sb = new StringBuilder();
        for (final Iterator<String> i : it) {
            if (!i.hasNext()) {
                break outer;
            }
            sb.append(i.next());
        }
        combined.add(sb.toString());
    }
    for (final Iterator<String> i : it) {
        if (i.hasNext()) {
            throw new IllegalArgumentException("Lists not the same length.");
        }
    }
    return combined;
}
Comments