2

I am new to java. I have done python before and concatenating elements of two lists or arrays seemed easy with loop. But how to do the same with java??? For example, I have a multidimensional array: //codes

String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};

//The output I am expecting :

Mr. Jones, Mrs. Jones, Ms, Jones, etc.

// I can do it by handpicking elements from indices, as shown in oracle documentation, but what I am looking for is a loop to do the job instead of doing: //code

System.out.println(nameAry[0][0]+", "+nameAry[1][0]);

` ////So, is there a way to put it the way I do in python,i.e.,:

x=["Mr.","Mrs.","Ms."]
y=["Jonse","patel"]
names-[a+b for a in x for b in y]

///this gives me the following result:

['Mr.Jonse', 'Mr.patel', 'Mrs.Jonse', 'Mrs.patel', 'Ms.Jonse', 'Ms.patel']

//So, is there something like this in Java???

3
  • It's called a cartesian product. Commented Aug 15, 2017 at 6:46
  • Just do the same thing as in Python: a for loop executing another for loop. The syntax is different, but the principle is the same. Commented Aug 15, 2017 at 6:50
  • I thought so too. But here what I was targeting was to do same thing to a multidimensional array as I did to python lists. I mean, is it possible? Commented Aug 15, 2017 at 10:19

3 Answers 3

2

You can just use loops with index variables to access your array. Here I'm using i to loop through the first dimension and j for the second dimension of the string array, while assembling each pair and adding it to a list. The part with the ArrayList is just for convenience, you can also return the strings or add them to a different data structure. Hope that helps.

Edit: Explanations

  ArrayList<String> list = new ArrayList<String>();
        String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};
        for(int i = 0;i<nameAry[0].length;i++) {
            for(int j =0;j<nameAry[1].length;j++) {
                list.add(nameAry[0][i]+nameAry[1][j]);
            }
        }
Sign up to request clarification or add additional context in comments.

4 Comments

Please explain your answer.
this is super awesome...!! The method is so easy!!!! I was afraid that I cannot do the with Java what I did with python!! But different dimensions should just be put through different 'for loop' and 'various indices should be marked as different ones'....Excellent ...I love it. Thanks a lot.
by the way any imports needed?
Yes you need to import java.util.ArrayList. Hope I could answer your question.
2

Here's a solution using streams.

String [][] nameAry={{"Mr.","Mrs.","Ms."},{"Jones","Patel"}};
List<String> list = Arrays.stream(nameAry[0])
    .flatMap(x -> Arrays.stream(nameAry[1])
        .map(y -> x + y))
    .collect(Collectors.toList());
list.forEach(System.out::println);

Note that the flatMap method is used here. It is used to turn each element of the first subarray into a new stream. The new stream is created by .map(y -> x + y) i.e. concatenating the names to the honorifics. All the new streams are then joined.

1 Comment

@user7360021 The three imports you need are java.util.List, java.util.Arrays and java.util.stream.Collectors. Also, if you think my answer answers your question, please consider accepting it by clicking on that checkmark!
-1

I think the use of a 2D array here as input is wrong. You have correctly used 2 arrays as inputs in your Python example. So just do the same in Java.

Cartesian product method:

public String[] cartesianProduct(String[] first, String[] second) {
  String[] result = new String[first.length * second.length];
  int resIndex=0;

  for (int i=0; i < first.length; i++) {
    for (int j=0; j < second.length; j++) {
      result[resIndex] = first[i] + second[j];
      resIndex++;
    }
  }
}

Method main:

public static void main(String[] args) {
  String[] nameArr = {"Jones","Patel"};
  String[] prefixArr = {"Mr.","Mrs.","Ms."};
  String[] result = cartesianProduct(prefixArr, nameArr);

  // Here you can print the result 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.