Java 8 jdk8 constructor reference

static class Person {
        private int id;

        public Person(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Person{id=" + id + '}';
        }
    }

    public static void main(String[] args) {
        IntStream
                .range(0, 3)
                // .map(n -> new Person(n)) // does not compile since lambda return type is expected to be int
                .mapToObj(Person::new) // alternative to .mapToObj(n -> new Person(n))
                .forEach(System.out::println);
    }

Output:

Person{id=0}
Person{id=1}
Person{id=2}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s