我有一个代码,该代码填充了两个int []数组,该数组的数字为0-255。我需要使读取文件,然后将所有其他整数分组在一起,例如,我的文件是0 12 85 45 20 14 255 145,我需要做对的成对,将是0-12、85-45、20-14,255-145。你有什么建议吗?
try {
DataInputStream dis = new DataInputStream(new FileInputStream(new File("input.txt")));
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("output.txt")));
int[] i = new int[256];
int[] j = new int[256];
for (int k = 0; k < 256; k++) {
i[k] = k;
for (int l = 0; l < 256; l++) {
j[l] = l;
System.out.println(k + " " + l);
}
}
//the int pairing should be here
//but I have no idea how to pair the integers from the input.txt file
}
流api建议非常简洁的解决方案:
String string = Files.readString(Paths.get(PATH_TO_FILE)); // get file content
String[] arr = string.split(" ");
List<String> pairs = IntStream.iterate(0, n -> n < arr.length, n -> n + 2)
.mapToObj(i -> arr[i] + "-" + arr[i + 1])
.collect(Collectors.toList());
System.out.println(pairs); // [0-12, 85-45, 20-14, 255-145]