加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 导航不同对象的复杂树的最佳方法是什么?

发布时间:2020-12-15 00:41:13 所属栏目:Java 来源:网络整理
导读:例如: class Vehicle { CollectionAxle axles;}class Axle { CollectionWheel wheels;}class Wheel { // I think there are dually rims that take two tires -- just go with it CollectionTire tires;}class Tire { int width; int diameter;} 我有一项服
例如:
class Vehicle {
    Collection<Axle> axles;
}

class Axle {
    Collection<Wheel> wheels;
}

class Wheel {
    // I think there are dually rims that take two tires -- just go with it
    Collection<Tire> tires;
}

class Tire {
    int width;
    int diameter;
}

我有一项服务,通过它我可以获得我所知道的所有车辆对象的集合.现在说我有一个特定宽度和直径的轮胎,我想找到一辆可以接受它的车辆.简单的方法是有一组四个嵌套循环,如下所示:

for (Vehicle vehicle : vehicles) {
    for (Axle axle : vehicle.getAxles()) {
        for (Wheel wheel : axle.getWheels()) {
            for (Tire tire : wheel.getTires()) {
                if (tire.width == targetWidth
                 && tire.diameter == targetDiameter) {
                    // do something
                    break;
                }
            }
        }
    }
}

这有一个好的设计模式吗?还是要使用更好的数据结构?将某个指数保留在映射到车辆的轮胎信息的位置会更好吗?

编辑:回答评论中的问题

Do you have control over the structure of the data you receive from the service?

Do you need to search for different tires multiple times in the same data?

Is performance an issue?

不是特别

When you find the tire,do you just need to know which vehicle contains it or do you also need the axle and wheel?

有时只是车辆,有时只是车轴 – 两种不同的环境

Do you need the reference to the tire that was found?

是的,在我需要轴的情况下

EDIT2:
进一步扩展隐喻,解释上述两种情况:

背景1 – 我想知道车辆,所以我可以派一名工人去收集车辆并将其带回来

背景2 – 我想知道轴和轮胎,因为我正在尝试做这项工作的车辆

解决方法

您可以使用 Java 8 streams来展平循环.
vehicles.stream()
    .flatMap(vehicle -> vehicle.getAxles().stream())
    .flatMap(axle -> axle.getWheels().stream())
    .flatMap(wheel -> wheel.getTires().stream())
    .filter(tire -> tire.width == targetWidth
             && tire.diameter == targetDiameter)
    .forEach(tire -> {
        // do something
    });

关于流的好处是你可以在序列中的任何地方插入额外的过滤器,过滤器,findAny等等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读