java - 转换地图> 到地图>,使用 Java 8 流。我这样做了,但是没有 for 循环怎么做
问题描述
代码中的 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()));
推荐阅读
- java - 使用 JAXB 数据绑定的通用 CXF 基于 WSDL 的服务器
- scheme - Scheme中的letrec-syntax和let-syntax有什么区别?
- arraylist - 布局相同但数据不同的数组列表(CardView)
- resources - ModuleNotFoundError:尝试导入资源时没有名为“staty”的模块
- c# - 如何使用 httprequest 或 httpclient 将数据发布到网站 api
- php - Wordpress 元查询:搜索更小或更高的数值不起作用?
- aggregation-framework - kafka_Mongodb 同步连接器失败 ERROR WorkerSinkTask{id=mongo-sink-0} 任务被杀死,直到手动重新启动才能恢复
- sql - 选择生肖的 SQL 查询
- javascript - 通过父组件将数据从一个组件传递到另一个组件
- rdf - protege reasoner 不报告违反 GCI 的错误