从迭代器转换Java 8 Streams

时间:2015-03-17 06:19:06

标签: java java-8

private void applyQueryConditions(List resultList,             列出finalList){

    ListIterator<NestedCustomerDO50> iterator = resultList.listIterator();
    for (; iterator.hasNext();) {

        NestedCustomerDO50 nestedDo = iterator.next();

        if ('S' == nestedDo.getAttrib8()) {

            for (NestedFirstChildDO50 child : nestedDo.getFirstChildList()) {
                if (("ST2".equals(child.getAttrib18()))
                        || ("ST3".equals(child.getAttrib18()))
                        || ("ST4".equals(child.getAttrib18()) || (!"ST"
                                .equals(child.getAttrib18())))) {
                    if (null != child.getGrandChildList()) {
                        for (NestedGrandChildDO50 grandChild : child
                                .getGrandChildList()) {
                            if ((date.after(grandChild.getAttrib19()) && date
                                    .before(grandChild.getAttrib43()))) {

                                finalList.add(nestedDo);

                            }
                        }

                    }

                }

            }

        }

    }

}

我想将以下代码转换为Java 8 Streams。但我发现了困难。 NestedCustomerDO50是一个由NestedFirstChildDO50继承的类,它由NestedGrandChildDO50继承。每个类包含子类的List(即NestedCustomerDO50包含NestedFirstChildDO50的列表,NestedFirstChildDO50包含NestedGrandChildDO50的List)。每个类包含50个属性(attrib1-atrib50)。

List<NestedGrandChildDO50> testS = resultList.stream() 
.filter(v1 -> v1.getAttrib8() == 'S') 
.flatMap(value -> value.getFirstChildList().stream()) 
.filter(value -> "ST2".equals(value.getAttrib18()) 
|| "ST3".equals(value.getAttrib18()) || "ST4".equals(value.getAttrib18()) ||!("ST".equals(value.getAttrib18()))) 
.flatMap(value -> value.getGrandChildList().stream()) 
.filter( val2 -> (date.after(val2.getAttrib19())) && (date.before(val2.getAttrib43()))) 
.collect(Collectors.toList());

这里我只获得GrandChild列表。但我希望ParentObject List满足条件。有没有办法做到这一点。请解释如何使用代码执行此操作。

1 个答案:

答案 0 :(得分:0)

使用Stream-API的filter-method。 nestedDO.getFirstChildList().stream().filter(c -> { String attr18 = c.getAttrib18(); ...//your comparison }).forEach(c -> { ...//do something with the matching children });

resultList.stream().
     filter(nestedDo -> nestedDo.getAttrib8() == 'S').
     filter(nestedDo ->  
         nestedDo.getFirstChildList().stream().anyMatch(c -> 
             ("ST2".equals(c.getAttrib18()) || 
             "ST3".equals(c.getAttrib18()) || 
             "ST4".equals(c.getAttrib18()) || 
             !"ST".equals(c.getAttrib18())) &&
             c.getGrandChildList() != null &&
             c.getGrandChildList().stream().anyMatch(gc -> {
                   date.after(gc.getAttrib19()) &&
                   date.before(gc.getAttrib43())
             }))
         ))).
     forEach(finalList.add(nestedDo));

由于你的方法多次将nestedDo添加到finalList,我已经纠正了这个问题。现在每个匹配的嵌套Do只添加一次。