【问题标题】:Converting nested for loops with JAVA8 filter使用 JAVA8 过滤器转换嵌套的 for 循环
【发布时间】:2021-07-02 11:50:36
【问题描述】:
class MyObject {
  String key;
  String value;
}

我有两个列表,listAlistB 包含 MyObject 对象。

我正在尝试将以下嵌套的 for 循环转换为基于 Java8 的流:

for(String objA : listA) {
   for(String objB : listB) {
       if(objA.getKey().equals(objB.getKey()) && !objA.getValue().equals(objB.getValue())) {
           // create an object of a different class `MyDiff` with params as 
           // objA.getKey(), objA.getValue(), objB.getValue()
           // and push it to a list.
       }
   }
}

我尝试用 JAVA8 解决这个问题,

List<MyDiff> diff = listA.streams().filter(objA -> {
    listB.stream.anyMatch(objB -> objA.getKey().equals(obj.getKey()) && !objA.getValue().equals(obj.getValue()))
})

但是anyMatch 不返回一个对象,我不能用filter 代替它。

【问题讨论】:

    标签: java-8


    【解决方案1】:

    您可以使用flatMap()filter()运算符来完成。

    List<MyDiff> diff = 
        listA.stream().flatMap(objA ->
            listB.stream()
                 .filter(objB -> objA.getKey().equals(objB.getKey()) && !objA.getValue().equals(objB.getValue()))
                 .map(objB -> new MyDiff(objA.getKey(), objA.getValue(), objB.getValue())))
        .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2022-06-24
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 2019-11-10
      • 2012-11-06
      相关资源
      最近更新 更多