The for loop in the code is need to be replaced by java8 streams. How can I resolve this?
public class Conversion {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Person class (name, age , gender)
//Employee class (name, gender)
Map<String, List<Person>> mapPerson = new HashMap<String, List<Person>>();
Map<String, List<Employee>> employeeMap = new HashMap<>();
List<Person> personList1 = new ArrayList<Person>();
personList1.add(new Person("Adam", 22, "Male"));
personList1.add(new Person("Alon", 21, "Female"));
List<Person> personList2 = new ArrayList<Person>();
personList2.add(new Person("Chad", 23, "Male"));
personList2.add(new Person("Daina", 21, "Female"));
List<Person> personList3 = new ArrayList<Person>();
personList3.add(new Person("Mark", 22, "Female"));
personList3.add(new Person("Helen", 25, "Male"));
mapPerson.put("A", personList1);
mapPerson.put("B", personList2);
mapPerson.put("C", personList3);
for (Map.Entry<String, List<Person>> entry : mapPerson.entrySet()) {
String key = entry.getKey();
List<Person> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "n");
}
System.out.println("******************************************");
employeeMap = getEmployeeMap(mapPerson);
for(Map.Entry<String, List<Employee>> listMap : employeeMap.entrySet())
{
System.out.println("Key : " + listMap.getKey());
System.out.println("Values : " + listMap.getValue());
System.out.println("===============");
}
}
This is the for loop in the function for iteration of MAP. Instead of this I have to use streams.
public static Map<String, List<Employee>> getEmployeeMap(Map<String, List<Person>> personMap) {
Map<String, List<Employee>> employeeMap = new HashMap<>();
for(Map.Entry<String, List<Person>> listMap : personMap.entrySet()) {
String key = listMap.getKey();
List<Person> personList = listMap.getValue();
List<Employee> employeeList = personList.stream().map(p-> new Employee(p.getName(), p.getGender())).collect(Collectors.toList());
employeeMap.put(key, employeeList);
}
return employeeMap;
}
}
You can use Collectors.toMap
and modify the value inside it.
Map<String, List<Employee>> employeeMap =
mapPerson.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().stream().map(p-> new Employee(p.getName(), p.getGender())).collect(Collectors.toList()));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments