0

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?

1
  • 1
    First of all the result should be {2, 7, 1} Commented Mar 24, 2016 at 22:14

3 Answers 3

7

In you can do

int[] xCoords = Stream.of(points).mapToInt(p -> p.x).toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Well, just for having used streams +1 :D
I KNEW it was possible using lambda functions!
5

If you're using

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

2 Comments

Thank you very much! Now it just depends on which of the two options is more efficient, but I guess it just comes down to styling.
@Busti Both solutions work. It depends on the level of encapsulation :).
4

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()};
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.