Function Object in Java

后端 未结 5 777
醉话见心
醉话见心 2021-02-03 11:32

I wanna implement a javascript like method in java , is this possible ?

Say , I have a Person class :

public class Person {
 private String name ;
 priva         


        
5条回答
  •  旧时难觅i
    2021-02-03 12:25

    import java.util.Arrays;
    import java.util.List;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class FuntionAsParameter {
    
    
        public static void main(final String[] args) {
    
            Person p1 = new Person("Jenny", 20);
            Person p2 = new Person("Kate", 22);
    
            List pList = Arrays.asList(new Person[]{p1, p2});
    
            Function, List> theFunction = Function.>identity()
                .andThen(personList -> personList
                    .stream()
                    .map(person -> new Person(person.getName(), person.getAge() + 1))
                    .collect(Collectors.toList()));
    
            // You can use this directly
            List directly = theFunction.apply(pList);
            directly.forEach(person -> System.out.println(person));
    
            // Or use it as an input parameter
            List toMethod = modList(pList, theFunction);
            toMethod.forEach(person -> System.out.println(person));
    
            // Or you might prefer this way
            List thirdWay = modList(pList,
                    (list) -> list.stream()
                            .map(person -> new Person(person.getName(), person.getAge() + 1))
                            .collect(Collectors.toList())
            );
            thirdWay.forEach(person -> System.out.println(person));
        }
    
        private static List modList(List personList, Function, List> theFunction) {
            return theFunction.apply(personList);
        }
    
    
    }
    
    class Person {
    
        private String name;
        private int age;
    
        public Person(final String name, final int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
        }
    }
    

提交回复
热议问题