使用 Java 8 流将 Map<String,List> <Person>转换为 Map<String,List<Employee>>。我这样做了,但



代码中的 for 循环需要替换为 java8 流。我该如何解决这个问题?

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("===============");
}
}

这是用于迭代 MAP 的函数中的 for 循环。取而代之的是,我必须使用流。

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;
}   
}

您可以使用Collectors.toMap并修改其中的值。

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()));

最新更新