How to Extract a Properties from an Object using Java 8 Stream

In this tutorial, you will learn, How to extract a properties from an object using Java 8 stream API`s and same properties can be collected as a List object. This example program has been tested and shared in the same post.

How to Extract a Properties from an Object using Java 8 Stream
How to Extract a Properties from an Object using
Java 8 Stream

Example Program

The following example contains two classes one is Customer class and another one is Example class. The customer class is a simple POJO (Plain Old Java Object) class, which contains following properties such as,

  • id – Customer Id
  • name – Customer Name
  • age – Customer Age

and also, it`s accepting the value for properties through constructor

public Customer(int id, String name, int age) {
	this.id = id;
	this.name = name;
	this.age = age;
}

Customer Class

package com.dineshkrish;

/**
 * @author Dinesh Krishnan
 */

public class Customer {

    private int id;
    private String name;
    private int age;

    public Customer(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

It can be achieved by using following snippet

 
customerList
	.stream()
	.map(Customer::getId)
	.collect(Collectors.toList());

Example Class (Complete Example – Main Class)

package com.dineshkrish;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Dinesh Krishnan
 */

public class Example {

    public static void main(String[] args) {

        List<Customer> customerList = new ArrayList<Customer>();

        customerList.add(new Customer(101, "Dinesh", 20));
        customerList.add(new Customer(102, "Krishnan", 30));
        customerList.add(new Customer(103, "John", 40));
        customerList.add(new Customer(104, "Robert", 25));
        customerList.add(new Customer(105, "Smith", 35));

        List<Integer> ids = customerList
                .stream()
                .map(Customer::getId)
                .collect(Collectors.toList());

        List<String> names = customerList
                .stream()
                .map(Customer::getName)
                .collect(Collectors.toList());

        List<Integer> ages = customerList
                .stream()
                .map(Customer::getAge)
                .collect(Collectors.toList());

        System.out.println(ids);
        System.out.println(names);
        System.out.println(ages);
    }
}

Output

[101, 102, 103, 104, 105]
[Dinesh, Krishnan, John, Robert, Smith]
[20, 30, 40, 25, 35]

References