Thursday 31 August 2017

How to get name values from a list of Software engineer objects using Java 8 streams


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=c47IfvJPRUo&list=UUhwKlOVR041tngjerWxVccw

SoftwareEngineer.java
public class SoftwareEngineer
{
    private String name;
    private int age;
    private int salary;

    public SoftwareEngineer(String name, int age, int salary)
    {
        super();
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

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

    public int getSalary()
    {
        return salary;
    }

    public void setSalary(int salary)
    {
        this.salary = salary;
    }

}
StreamDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
List of objects -> List of String
Get all the name values from a list of the SoftwareEngineer objects.
*/

public class StreamDemo
{
    public static void main(String[] args)
    {

        List<SoftwareEngineer> softwareEngineerList = Arrays.asList(
                new SoftwareEngineer("Ram", 30, 10000),
                new SoftwareEngineer("Peter", 27, 20000),
                new SoftwareEngineer("Jai", 33, 30000));

        // Before Java 8
        List<String> nameList = new ArrayList<String>();
        for (SoftwareEngineer softwareEngineer : softwareEngineerList)
        {
            nameList.add(softwareEngineer.getName());
        }
        System.out.println(nameList);

        // Java 8
        List<String> collectNameList = softwareEngineerList.stream()
                                                .map(softwareEngineer -> softwareEngineer.getName())
                                                .collect(Collectors.toList());
        System.out.println(collectNameList);

    }

}
Output
[Ram, Peter, Jai]
[Ram, Peter, Jai]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_name_swl_stream_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_name_swl_stream_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/53e39342c1c41555c6e548783b3cf96ab7bd9ee6/BasicJava/StreamDemo_name_swl_stream_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment