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 – 我想知道轴和轮胎,因为我正在尝试做这项工作的车辆
解决方法
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等等.
原文地址:https://www.jb51.cc/java/129466.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。