0

I am very new to java and I am currently trying to recreate some python code in java. This is my problem:

I have 2 different variables:

    ArrayList <Double> x_loc= new ArrayList<>();
    ArrayList <Double> y_loc= new ArrayList<>();

They both represent coordinates. My goal is to now create a 2-dimensional array with both of them so I could have something like array([[x1,y1],[x2,y2],...]).

I've thought about creating a new ArrayList and then adding each individual item:

ArrayList<Double[]> data_fin = new ArrayList<>(); 
data_fin.add(x_loc)

However, this doesn't work. I know I'm probably doing something very stupid but, as a newbie, I'd really appreciate your help. Thanks!

J.Doe
  • 529
  • 4
  • 14
  • 3
    Why don't you create a class that holds two coordinate values? – deHaar Nov 19 '19 at 15:15
  • I would suggest using `double[]` over `Double[]`. I think creating a new class is better solution though. – matt Nov 19 '19 at 15:19
  • Or you can use the `zip` operator: https://stackoverflow.com/questions/31963297/how-to-zip-two-java-lists – Enrico Florentino Nov 19 '19 at 15:20
  • You could also use a double list like List> this creates a two dimensional list and you won't have the complexity of index matching between the two separated arrays – Sergio Arrighi Nov 19 '19 at 15:20

1 Answers1

2

You have to iterate over the original Lists in order to populate the combined List:

for (int i = 0; i < x_loc.size() && i < y_loc.size(); i++) {
    data_fin.add (new Double[]{x_loc.get(i),y_loc.get(i)});
}

It can also be done with Streams:

List<Double[]> data_fin = IntStream.range(0,x_loc.size())
                                   .mapToObj(i -> new Double[] {x_loc.get(i),y_loc.get(i)})
                                   .collect(Collectors.toList());

(Here I assumed both input Lists have the same size).

Eran
  • 387,369
  • 54
  • 702
  • 768