LambdaJ forEach设置

Tap*_*ose 5 java collections lambdaj

我想将值设置为对象的字段,以便它首先获取该字段的先前值并向其追加内容并将其设置为该字段.

在LambdaJ中forEach我们可以这样做:

forEach(myCollection).setFieldValue("someValue");

但我需要的是:

forEach(myCollection).setFieldValue(getFieldValue() + "someValue");

LambdaJ有可能吗?

Spi*_*zzy 1

我有一个类似的用例,并意识到 forEach 对我的使用方式没有帮助。

所以我认为闭包是一个解决方案:

@Test
public void test() {
    Closure modify = closure();{
        of(Point.class).setLocation(var(Point.class).x+10, 10);          
    }

    List<Point> points = new ArrayList<>();
    points.add(new Point(10, 0));
    points.add(new Point(10, 10));

    modify.each(points);

    for (Point point : points) {
        assertEquals(20, point.getX(), 0.0);
    }
}
Run Code Online (Sandbox Code Playgroud)

但断言失败,因为集合中的对象未被修改。也许我在那里做错了什么。

最后我使用了 apache commons 集合中的闭包。

更新

我能够通过闭包解决这个难题。看来你不能直接使用自由变量。这是工作代码:

@Test
public void test() {
    Closure modify = closure();{
        of(this).visit(var(Point.class));
    }

    List<Point> points = new ArrayList<Point>();
    points.add(new Point(10, 0));
    points.add(new Point(10, 10));

    modify.each(points);

    for (Point point : points) {
        assertEquals(20, point.getX(), 0.0);
    }
}

void visit(Point p) {
    p.setLocation(p.x + 10, p.y);
}
Run Code Online (Sandbox Code Playgroud)

注意:this您也可以编写一个包含该visit方法的类,并在closure.