Reputation: 11
I am following a Stream tutorial but I do not understand what I need to do to have the List elements output the content as the numbers contained within.
Given two lists of numbers, how would you return all pairs of numbers? For example, given a list [1, 2, 3] and a list [3, 4] you should return [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]. For simplicity, you can represent a pair as an array with two elements.
I have read a few posts about overriding toString() but I have no object to override. I am clearly missing something about the nature of 'pairs', is it because 'pairs' is a List of int[][]?
package testcode;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class TestCode {
public TestCode(){
testStream();
}
public static void main(String[] args) {
TestCode tC = new TestCode();
}
public void testStream(){
List<Integer> numbers1 = Arrays.asList(1,2,3);
List<Integer> numbers2 = Arrays.asList(3,4);
List<int[]> pairs = numbers1.stream()
.flatMap(i -> numbers2.stream()
.map(j -> new int[]{i, j})
)
.collect(toList());
pairs.forEach(System.out::println);
//I have also tried
//String a = Arrays.toString(pairs); // but no suitable method found.
String list = pairs.toString();
System.out.println("list = " + list);
//tried converting pairs element to a List<String> using concatenation to force it be a string.
List<String> stringsList = new ArrayList<String>(pairs.size());
for (int i = 0 ; i < pairs.size() ; i++) {
stringsList.add("" + pairs.get(i));
}
stringsList.forEach(System.out::println);
// or
System.out.println(" ** test 2");
String[] stringsList2 = new String[pairs.size()];
for (int i = 0 ; i < pairs.size() ; i++) {
stringsList2[i] = "" + pairs.get(i);
System.out.println(stringsList2[i]);
}
}
Cheers for reading.
Upvotes: 0
Views: 842
Reputation: 16711
Just use a nested for
loop to cycle through the arrays and concatenate casted strings.
public static String test_method() {
int[] array1 = {1, 2, 3};
int[] array2 = {3, 4};
String string = "";
for (int i: array1) {
for (int j: array2) {
String sub = "(" + String.valueOf(i) + ", "
+ String.valueOf(j) + ") ";
string += sub;
}
}
return string;
}
Upvotes: 1
Reputation: 1832
Arrays.deepToString(Object[] a)
should accomplish what you need.
deepToString
will recursively print the elements of a multidimensional array.
Code
import java.util.Arrays;
public class Test{
public static void main(String[] args){
int[][] test = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(Arrays.deepToString(test));
}
}
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: 1