Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

lambda - How to convert java list of objects to 2D array?

Is there an easy way to use lambda in java 8 to convert

from this object:

        "coords" : [ {
    "x" : -73.72573187081096,
            "y" : 40.71033050649526
}, {
    "x" : -73.724263,
            "y" : 40.709908}
]

to this object:

    "coordinates":[
    [
    [
   -73.72573187081096,
            40.71033050649526
    ],
    [
    -73.724263,
            40.709908
    ]]

I try to use transform() function but how can i transform from list to 2D array ?

here is my try, but i got an error:

coordinates =

        Lists.newArrayList(
                Lists.newArrayList(
                        Lists.newArrayList(
                                coords.stream()
                                        .map( item -> Lists.newArrayList(ImmutableList.of(item.x, item.y))))));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not 100% sure what you are asking, but I'll give it a try. Assuming you have a list of Points...

List<Point2D> points = Arrays.asList(new Point2D.Double(12., 34.),
                                     new Point2D.Double(56., 78.));

... you can turn that list into a 2D-array like this:

double[][] array = points.stream()
        .map(p -> new double[] {p.getX(), p.getY()})
        .toArray(double[][]::new);

... or into a nested list like this:

List<List<Double>> list = points.stream()
        .map(p -> Arrays.asList(p.getX(), p.getY()))
        .collect(Collectors.toList());

In both cases, the result looks like this [[12.0, 34.0], [56.0, 78.0]], as an array or a list, respectively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...