Function objects in Java

I want to implement a JavaScript method in Java. Is this possible?

Say, I have a person class:

public class Person {
 private String name ;
 private int age ;
 // constructor,accessors are omitted
}

And a list of person objects:

Person p1 = new Person("Jenny",20);
Person p2 = new Person("Kate",22);
List<Person> pList = Arrays.asList(new Person[] {p1,p2});

I want to implement such a method:

modList(pList,new Operation (Person p) {
  incrementAge(Person p) { p.setAge(p.getAge() + 1)};
});

Modlist takes two parameters, one is the list and the other is the "function object". It loops the list and applies the function to each element in the list In the functional programming language, this is very simple. I don't know what Java does? Maybe it can be done through dynamic proxy. Is there a performance tradeoff compared with the native for loop?

Solution

You can use an interface and an anonymous inner class to implement it

Person p1 = new Person("Jenny",22);
List<Person> pList = Arrays.asList(p1,p2);

interface Operation {
  abstract void execute(Person p);
}

public void modList(List<Person> list,Operation op) {
  for (Person p : list)
    op.execute(p);
}

modList(pList,new Operation {
  public void execute(Person p) { p.setAge(p.getAge() + 1)};
});

Note that using varargs in Java 5, you can simplify the search for arrays Aslist call

Update: above version:

interface Operation<E> {
  abstract void execute(E elem);
}

public <E> void modList(List<? extends E> list,Operation<E> op) {
  for (E elem : list)
    op.execute(elem);
}

modList(pList,new Operation<Person>() {
    public void execute(Person p) { p.setAge(p.getAge() + 1); }
});

Note that through the above definition of modlist, you can perform "operation" > in the list < student > (provide that the student is a subclass of person) This is not allowed for normal list < E > parameter types

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>