LambdaJ forEach设置

时间:2013-11-01 07:59:16

标签: java collections lambdaj

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

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

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

但我需要的是:

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

LambdaJ有可能吗?

2 个答案:

答案 0 :(得分:4)

我知道你问过LambdaJ,我很好奇,因为这是一个常见的问题。

我对我做的结果感到惊讶:

forEach(list).setName(on(User.class).getName() + "someValue");

我虽然会回答你的问题。

所以,我尝试了一种使用Guava功能方式的不同方法。它可以为你工作所以我会发布答案(但如果你不同意我可以删除它):

番石榴功能方法:

    @Test
    public void test_applyPreviousValue() {

         List<User> filteredList = Lists.newArrayList(new User("Fede", 20), new User("Peter", 12), new User("John", 41));

         Function<User, User> getType = new Function<User, User>() {
             public User apply(User input) {
                  input.setName(input.getName()+"someValue");
                  return input;
             }
         };

         Collection<User> result = Collections2.transform(filteredList, getType);
         System.out.println(result);
     }

希望能提供帮助

答案 1 :(得分:1)

我有一个类似的用例,并意识到每个人都不会帮助我使用它。

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

@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);
    }
}

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

最后我使用了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);
}

注意:您也可以编写一个包含this方法的类,而不是visit,而是在closure的定义中使用它。