Java 8 streams demo part 2: Stream of custom objects

11 07 2015

Following the List with primitive types like in post here: Java 8 Streams demo, now it’s time to demonstrate streams with custom objects. Please read mentioned post first to get the idea of this one faster.

Introduction

Now I want to have a list of Users. User is a POJO having a name and age. I am going to filter out users younger than 18 years and sort them in list by their age, ascending. At the beginning I have a list of users:

List<User> users = new ArrayList<User>();
users.add(new User("John", 21));
users.add(new User("Jack", 13));
users.add(new User("Joe", 56));
users.add(new User("Michelle", 37));

Filtering and sorting stream
I convert the list to the stream with the stream() method, filter and sort items. Item is now the User class instance, so I can call its instance methods like getAge().

users.stream()
        .filter(item -> item.getAge() > 18)
        .sorted((item1, item2) -> (item1.getAge() - item2.getAge()))
        .forEach(System.out::println);

Result
As a result I get adult users, sorted by age:

User{name='John', age=21}
User{name='Michelle', age=37}
User{name='Joe', age=56}

Source Code

Find the source Code for this tutorial on my github: https://github.com/yacekmm/Java8Streams/tree/StreamWithObject


Actions

Information

Give Your feedback:

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




%d bloggers like this: