配对两个整数,并从文件中每隔一个整数

时间:2019-02-24 17:34:37

标签: java int

我有一个代码,该代码用0-255之间的数字填充两个int []数组。 我需要读取一个文件,然后将其他所有整数组合在一起,例如我的文件是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
}

1 个答案:

答案 0 :(得分:1)

Stream 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]