如何将Java对象列表转换为2D数组? [英] How to convert java list of objects to 2D array?

查看:59
本文介绍了如何将Java对象列表转换为2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在Java 8中使用lambda进行转换

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

从该对象开始:

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

此对象:

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

我尝试使用 transform()函数,但是如何从列表转换为2D数组?

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

推荐答案

不是100%知道您要问什么,但我会尝试一下.假设您有一个积分列表...

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.));

...您可以将该列表转换为2D数组,如下所示:

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

在两种情况下,结果分别看起来像这样 [[12.0,34.0],[56.0,78.0]] ,作为数组或列表.

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

这篇关于如何将Java对象列表转换为2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆