简体   繁体   中英

How can I put all the values of pair array to an simple array

How can I convert a pair array to a simple array as show below?

class Pair {
    int x;
    int y;

    public Pair(int a, int b){
        x = a;
        y = b;
    }
}

// you are given an array of this pair class
Pair[] p = {new Pair(5, 24), new Pair(39, 60), new Pair(15, 28),
            new Pair(27, 40), new Pair(50, 90)};

// I want to covert this into a simple array like
int[] arr = {5, 24, 39, 60, 15, 28, 27, 40, 50, 90};

As you can see I want to convert p into arr with each pair representing two numbers in the simple array.

Solution with streams:

int[] arr = Arrays.stream(pairs)
        .flatMapToInt(p -> IntStream.of(p.x, p.y))
        .toArray();

Solution with for-loop:

int[] arr = new int[2 * pairs.length];
for (int i = 0; i < pairs.length; i++) {
    arr[2*i] = pairs[i].x;
    arr[2*i + 1] = pairs[i].y;
}
  1. Create the second array to be twice the size of the first.
  2. Iterate over the first and add x and y to the second at the appropriate indexes.

Example:

int[] arr = new int[2 * p.length]; // make arr twice the size of p
for (int i = 0; i < p.length * 2; i += 2) {
    arr[i] = p[i / 2].x;
    arr[i + 1] = p[i / 2].y;
}

In my opinion, you have to iterate over the pair[] array and add the elements into a primitive int[] array.

here's an example code:

public int[] convertPairArrayToArray(pair[] pairs){
    int len = pairs.length;
    int[] ar = new int[len * 2];
    for (int i = 0; i < len; i++){
        ar[i] = pairs[i].x;
        ar[i + 1] = pairs[i].y;
        i = i + 1; // skip to the next 2 elements of int[]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM