java – 导航不同对象的复杂树的最佳方法是什么?
|
例如: 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;
}
}
}
}
}
这有一个好的设计模式吗?还是要使用更好的数据结构?将某个指数保留在映射到车辆的轮胎信息的位置会更好吗? 编辑:回答评论中的问题
是
是
不是特别
有时只是车辆,有时只是车轴 – 两种不同的环境
是的,在我需要轴的情况下 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等等. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
