How to get a list of specific fields values from objects stored in a list

What you will learn here about java stream API

  • How to get a list of specific fields values from objects stored in a list

Sometimes while working on java application or any java project we come to situation where we only want one field of java object. So here we will see how to get a list of specific fields values from objects stored in a list using stream API.

How to get a list of specific fields values from objects stored in a list

Simple java program for getting specific fields values from objects stored in a list.

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

public class Person {

	String firstName;
	String lastName;
	int age;
	
	public static void main(String[] args) 
	{
		List  person=new ArrayList();
		
		Person p1=new Person("john","Dow",55);
		Person p2=new Person("john","Cena",45);
		Person p3=new Person("john","Abhraham",35);
		
		person.add(p1);
		person.add(p2);
		person.add(p3);
		
		System.out.println("Returning only lastName of Person Object : ");
		/*Using map we can do this*/
		List FilteredLastName=person.stream().map(p->p.lastName).collect(Collectors.toList());
		
		System.out.print(FilteredLastName);

	}

	public Person(String firstName, String lastName, int age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public Person() {
		super();
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

OUTPUT

Returning only lastName of Person Object :
[Dow, Cena, Abhraham]

You may also like...