1

What would be the best way to convert two lists into 2D Array? Example

listA = {"A","B"}
listB = {"1","2"}

I want to convert them to: array = {{A ,1}, {B ,2}}

Is there a better way than doing it with manually with loops?

aphex
  • 3,372
  • 2
  • 28
  • 56
  • Please define "better" ... – Seelenvirtuose Apr 08 '16 at 10:16
  • 3
    It is called `zip()` and you can do it using a few third-party libraries such as Guava and Functional Java, each time with some quirks. – alamar Apr 08 '16 at 10:24
  • http://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip – Yosef Weiner Apr 08 '16 at 10:27
  • 1
    If by chance you are using doubles (not String) then apache math commons has a way to do it http://stackoverflow.com/questions/19292950/how-to-get-the-transpose-of-a-matrix-array-in-java – vikingsteve Apr 08 '16 at 10:52
  • @alamar: I'm not sure that 'zip()' the right name is. The examples I found are 2 arrays into one combining them like that: {"A","1","B","2"}. This is not a 2D Array with 2 columns. – aphex Apr 08 '16 at 11:28

1 Answers1

1

I am not sure what is your want. Just doing simplest way as below. Here, I assume listA and listB are same size.

List<String> listA = new ArrayList<String>();
listA.add("A");
listA.add("B");
listA.add("C");
List<String> listB = new ArrayList<String>();
listB.add("1");
listB.add("2");
listB.add("3");
String[][] multi = new String[listA.size()][listB.size()];
for(int i=0; i < listA.size(); i++) {
    multi[i] = new String[]{listA.get(i), listB.get(i)};
}
System.out.println(multi[0][0] + "," + multi[0][1]);
System.out.println(multi[1][0] + "," + multi[1][1]);
System.out.println(multi[2][0] + "," + multi[2][1]);

Output

A,1
B,2
C,3
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131