Reputation: 5604
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
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
Reputation: 21975
If you're using java-8
int[] xCoords = Stream.of(points).mapToInt(Point::getX).toArray();
Upvotes: 5
Reputation: 533530
In java-8 you can do
int[] xCoords = Stream.of(points).mapToInt(p -> p.x).toArray();
Upvotes: 7