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.
printffor printing you pairs:System.out.printf("(%d,%d)\n",pair[0],pair[1])). It might just be my opinion, but it looks a bit cleaner than all that string concatenation.