简体   繁体   中英

Converting two arraylist to a 2D string

While developing an application i come across a situation as below:

I have two Arralylists - list1, list2 which have values like:

list1 = [district1, district2, district3, district4, district5]
list2 = [service1, service2, service3, sevice4, service5]

Now i want to store the values in a third arraylist, list3 which will be like:

list3 = [district1, service1, district2, service2, district3, service3, district4, service4, district5, service 5]

Now i need to convert list3 to a two dimensional String (values[][]) which will be like:

values = [ [district1, service1], [district2, service2], [district3, service3], [district4, service4], [district5, service 5]]

Basically i need values[][]. I am not sure whether list3 is required or not. I spend the whole day working on this, bt couldnot figure out a solution. Would really appreciate someone's help. Thanks in advance.

Assuming the lists contain String and list1.size() == list2.size() :

String[][] values = new String[list1.size()][2];
for (int i = 0; i < list1.size(); i++) {
    values[0] = list1.get(i);
    values[1] = list2.get(i);
}

If list1 and list2 have same # of elements then something like following code should work for you:

String[][] list3 = new String[list1.size()][2];

for (int i=0; i<list1.size(); i++) {
   list3[i][0] = list1.get(i);
   list3[i][1] = list2.get(i);
}

Assuming both the lists are of same size, following code would help:

public String[][] merge(List<String> list1, List<String> list2) {
        String[][] values = new String[list1.size()][];

        for(int i=0 ; i< list1.size() ; i++){
            values[i] = new String[2];
            values[i][0] = list1.get(i);
            values[i][1] = list2.get(i);
        }
        return values;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM