【问题标题】:how to avoid a nested for loop in this problem在这个问题中如何避免嵌套的for循环
【发布时间】:2021-12-18 18:09:54
【问题描述】:

给定这些对象

测试

 int one;
 int two;
 List<AnotherObject> testList.

另一个对象

 string name;
 int three; 
 List<AthirdObject> anotherList;

AThirdObject

 string surname;
 int    id;
 

假设我们有 List 我怎样才能在不使用嵌套 for 循环的情况下到达 AThirdObject,谢谢

【问题讨论】:

  • 代码中的某些内容将执行嵌套循环,无论您是否真的看到它。
  • 我有点知道,但它更像是语法糖
  • 你想获取所有元素还是只获取一个?
  • 我想要所有元素

标签: java loops optimization java-8 nested


【解决方案1】:

Stream::flatMap 应该在这里使用,以提供对嵌套列表最低级别的“访问”,假设 getter 在示例类中正确实现:

List<Test> input = ...; // define input data

List<AThirdObject> nestedList = input
    .stream() // Stream<Test>
    .flatMap(t -> t.getTestList().stream()) // Stream<AnotherObject>
    .flatMap(ao -> ao.getAnotherList().stream()) // Stream<AThirdObject>
    .collect(Collectors.toList());

【讨论】:

  • 感谢您的回答,感谢您花时间实施它并且它有效
猜你喜欢
  • 2012-06-25
  • 2021-09-29
  • 2017-09-20
  • 1970-01-01
  • 2021-08-19
  • 2017-08-27
  • 2017-11-11
  • 2015-01-24
  • 1970-01-01
相关资源
最近更新 更多