-5
public class Employee {

    Integer id;
    String name;
}

I have a List of String containing the name of the employees.

i.e.

List<String> l = {"john","mike","jacky"};

I want to convert the String l into the list of Employee where the name will be from list l and if will be static 1 for each of them.

The final list should be like:

List<Employee> empList = ({1,"john"},{1,"mike"},{1,"jackey"})

How I can do it in java 8?

khelwood
  • 55,782
  • 14
  • 81
  • 108
nitin
  • 1
  • 1

2 Answers2

0

This might work ,I just took the arrays initially instead of List ,you can convert that into list

import java.util.*;
import java.util.stream.Collectors;

 class Employee {

    Integer id;
    String name;
    public Employee  setName(String name)
    {
      this.name=name;

      return this;
    }
    public String getName()
    {
     return this.name;
    }
}

class Main {
  public static void main(String[] args) {
    List<String> l =  Arrays.asList("john", "mike", "jackey", "dan");

 List<Employee> collect = l.stream().map(el->new Employee().setName(el)).collect(Collectors.toList());

    System.out.println(collect.get(0).getName());

      System.out.println(collect.get(1).getName());

        System.out.println(collect.get(2).getName());
  }
}

See the link

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
-1

Change your Employee.java like this:

public class Employee {

    static Integer id;
    String name;

    public Employee(){  id = 1; }

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

    public Integer getId(){ return id;  }
    public void setId(Integer id){  this.id = id;    }
}

Now you can use the employee class to add those names into a list like this:

import java.util.*;

public class Start{
    public static void main(String[] args) {
        String[] l = new String[]{"john","mike","jacky"};
        List<Employee> eList = new Vector<>();

        for(String name: l){
            Employee e = new Employee();
            e.setName(name);
            eList.add(e);
        }

        for(Employee e : eList){
            System.out.println(e.getId()+" "+e.getName() );
        }
    }
}
Qazi Fahim Farhan
  • 2,066
  • 1
  • 14
  • 26