Its not to concatenate but to merge two arrays so that they become array of name value pairs.
firstarray = ["a","aa","aaa"]
secondarray = ["b","bb","bbb"]
result = [["a","b"],["aa","bb"],["aaa","bbb"]]
What is the best way to do it?
Its not to concatenate but to merge two arrays so that they become array of name value pairs.
firstarray = ["a","aa","aaa"]
secondarray = ["b","bb","bbb"]
result = [["a","b"],["aa","bb"],["aaa","bbb"]]
What is the best way to do it?
in Java:
public static int [][] concat(int a[], int b[]) {
int res[][] = new int[a.length][2];
if (a.length != b.length) {
throw new IllegalArgumentException("lenght are not equal, cannot perform");
}
for (int i = 0; i < a.length; i++) {
res[i][0] = a[i];
res[i][1] = b[i];
}
return res;
}
I would recommend you use the Java collection classes, and avoid using arrays. Only use arrays if/when you have to do so (for performance reasons, for example). Otherwise, stick with learning and becoming much more proficient with the Java Collections API.
If I were to approach this problem, assuming the first list had unique items (i.e. no duplicates), I would have two instances of List (as opposed to arrays). And then I would create an instance of Map into which I would place the contents of the two lists. LinkedHashMap is used to ensure the order of the items from the first list are preserved.
Here's the example code:
List<String> first = Arrays.asList(new String[] {"a", "aa", "aaa"});
List<String> second = Arrays.asList(new String[] {"b", "bb", "bbb"});
Map<String, String> keyValuePairs = new LinkedHashMap<String, String>();
for (int i = 0, count = first.size(); i < count; ++i) {
keyValuePairs.put(first.get(i), second.get(i));
}
If one cannot assume the first list has unique values, then I would use List<List<String>>. Here's the example code:
List<String> first = Arrays.asList(new String[] {"a", "aa", "aaa"});
List<String> second = Arrays.asList(new String[] {"b", "bb", "bbb"});
List<List<String>> listOfList= new ArrayList<List<String>>();
for (int i = 0, count = first.size(); i < count; ++i) {
List<String> list = new ArrayList();
list.add(first.get(i));
list.add(second.get(i));
listOfList.add(list);
}
I don't think I can reinforce this point enough - avoid the use of arrays unless there is no way to do what you want with the Java collection classes. The only time I ever use arrays is to eke out performance at a verifiable bottleneck. And even then, I try to find a design level way around improving performance as opposed to using Java arrays.
LinkedHashMap). I also believe that using arrays is faster than using collection classes. Also, this method you use here would fail if two items in the first array/list are equal.