我正在学习 Stream 教程,但我不明白需要做什么才能让 List 元素将内容输出为其中包含的数字。
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.
我读过一些关于重写 toString() 的文章,但我没有要重写的对象。我显然遗漏了一些关于“pairs”本质的东西,是因为“pairs”是一个 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]);
}
}
为阅读干杯。
最佳答案
只需使用嵌套的 for
循环即可循环遍历数组并连接强制转换的字符串。
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;
}
关于java将列表元素显示为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013027/