Busti
Busti

Reputation: 5604

Convert an Array objects to an Array of variables within that object

Basically what I want to do is this:

Point[] points = new Point[]{new Point(2, 3), new Point(7,8), new Point(1, 8)};
int[] xCoords  = new int[points.length];

for (int i = 0; i < points.lenght; i++) {
    xCoords[i] = points[i].x;
}

So that in the end I would end up with xCoords looking like this:

{2, 7, 8}

Is it possible to archive this in a more general fashion?

Upvotes: 0

Views: 51

Answers (3)

Darshan Mehta
Darshan Mehta

Reputation: 30819

You can do it by using a 2D array, e.g:

int[][] coordinates = new int[5][];
for(int i=0 ; i < points.size() ; i++){
    coordinates[i] = new int[]{points.get(i).getX(), points.get(i).getY()};
}

Upvotes: 4

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

If you're using

int[] xCoords = Stream.of(points).mapToInt(Point::getX).toArray();

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533530

In you can do

int[] xCoords = Stream.of(points).mapToInt(p -> p.x).toArray();

Upvotes: 7

Related Questions