Lambda 如何使用Java8将下面的代码编写成函数式
我不熟悉lambda表达式和函数编程。Lambda 如何使用Java8将下面的代码编写成函数式,lambda,java-8,functional-programming,Lambda,Java 8,Functional Programming,我不熟悉lambda表达式和函数编程。 我使用Java8编写了下面的代码片段 List<Employee> myList = new ArrayList<>(); Map<String, List<Integer>> mapOf = new HashMap<>(); mapOf.put("key1", Arrays.asList(1, 2, 3)); mapOf.put("key2", Arra
我使用Java8编写了下面的代码片段
List<Employee> myList = new ArrayList<>();
Map<String, List<Integer>> mapOf = new HashMap<>();
mapOf.put("key1", Arrays.asList(1, 2, 3));
mapOf.put("key2", Arrays.asList(4, 5, 6));
mapOf.put("key3", Arrays.asList(7, 8));
mapOf.forEach((k ,v) -> {
Employee emp = new Employee();
v.stream().forEach(o ->{
emp.setFirstName("John Doe");
myList.add(emp);
System.out.println("Posting Data for :: " + k + " :: " + o);
});
});
上述代码按预期工作,但它是一个意大利面代码。
我读过很多文章,说我们不应该在lambda表达式中使用{},因为这会使代码难以理解
因此,现在我正在尝试将其转换为函数方式。
请帮忙。这可能就是你想要的
ArrayList<Employee> myL = mapOf.entrySet()
.stream()
.map(en ->
en.getValue().stream()
.map(l ->{
Employee emp = new Employee();
emp.setFirstName("John Doe");
System.out.println("Posting Data for :: " + en.getKey() + " :: " + l);
return emp;
}).collect(Collectors.toList())
)
.collect(ArrayList::new, ArrayList::addAll,ArrayList::addAll);
ArrayList myL=mapOf.entrySet()
.stream()
.map(en->
en.getValue().stream()
.地图(l->{
员工emp=新员工();
emp.setFirstName(“约翰·多伊”);
System.out.println(“发布数据为:”+en.getKey()+“:”+l);
返回emp;
}).collect(收集器.toList())
)
.collect(ArrayList::new,ArrayList::addAll,ArrayList::addAll);
mapOf.forEach((k,v)->v.forEach(o->System.out.println(“发布数据为:“+k+”:“+o))如果只需要值mapOf.forEach((k,v)->v.forEach(System.out::println))代码>你试过什么?你到底被困在哪里了?我已经更新了代码并试图转换代码,抱歉,福克。你到底想在这里实现什么?
ArrayList<Employee> myL = mapOf.entrySet()
.stream()
.map(en ->
en.getValue().stream()
.map(l ->{
Employee emp = new Employee();
emp.setFirstName("John Doe");
System.out.println("Posting Data for :: " + en.getKey() + " :: " + l);
return emp;
}).collect(Collectors.toList())
)
.collect(ArrayList::new, ArrayList::addAll,ArrayList::addAll);