java循环嵌套map赋值,如何使用java流将嵌套for循环转换为Hashmap

I am trying to convert the below nested for loop into hashmap using java stream but i got struck in the collector step. Could you please help?

Existing code:

private static HashMap getOutput(List eList) {

HashMap outputList = new HashMap<>();

for (Employee employee : eList) {

List departmentList = employee.getDepartmentList();

for (Department department : departmentList) {

if (department.getType().equals(DepartmentType.SCIENCE)) {

outputList.put(employee.getName(),department.getDepartmentId()));

}

}

}

return outputList;

}

So far i tried:

private static HashMap getOutput(List eList) {

return eList.stream()

.flatMap(emp -> emp.getDepartmentList().stream()

.filter(dept -> dept.getType().equals(DepartmentType.SCIENCE))

.collect(HashMap::new, ???)

}

解决方案

It seems like your main issue is preserving the stream's current emp reference after you've done the flatMap. To keep this reference, you will need to flatMap to some sort of class that can hold both the Employee and Department - such as a generic Tuple (aka Pair).

Java doesn't have an intuitive Tuple class built into it's API, so your options are:

Use a 3rd party library that provides a Tuple class (e.g. javatuples)

DIY: Build your own generic Tuple class (see related SO question)

Quick: Add a private inner class which is specifically intended for this lambda

Edit:

The comments (thanks @Holger!) have enlightened that it appears that there are many departments per employee. My original code risks throwing an exception since there would be duplicate keys, while the OP's original code simply overwrites the map entries. Consider using the groupingBycollector and changing the return type of this method.

private static Map> getOutput(List eList) {

return eList.stream()

// get a stream of employee / department pairs

.flatMap(emp -> emp.getDepartmentList().stream().map(dep -> new EmployeeDepartmentPair(emp, dep))

// filter the departments to SCIENCE

.filter(x -> x.department.getType().equals(DepartmentType.SCIENCE))

// group departmentIds by employee name

.collect(Collectors.groupingBy(x -> x.employee.getName(), Collectors.mapping(x -> x.department.getDepartmentId(), Collectors.toList())))

}

Original (see above edit):

Here's some updated code using option 3:

private static Map getOutput(List eList) {

return eList.stream()

.flatMap(emp -> emp.getDepartmentList().stream().map(dep -> new EmployeeDepartmentPair(emp, dep))

.filter(x -> x.department.getType().equals(DepartmentType.SCIENCE))

.collect(Collectors.toMap(x -> x.employee.getName(), x -> x.department.getDepartmentId()));

}

private static class EmployeeDepartmentPair {

public final Employee employee;

public final Department department;

public EmployeeDepartmentPair(Employee emp, Department d) {

this.employee = emp;

this.department = d;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Java 中,可以使用第三方的工具将 Map 转换Java 对象。其中一种常见的方法是使用 Google 的 Gson 库。 首先,你需要在项目中添加 Gson 的依赖。然后,你可以使用 Gson 的 fromJson() 方法将 Map 转换Java 对象。例如: ``` Map<String, Object> map = new HashMap<>(); map.put("name", "John"); map.put("age", 30); Gson gson = new Gson(); Person person = gson.fromJson(gson.toJson(map), Person.class); System.out.println(person.getName()); // prints "John" System.out.println(person.getAge()); // prints 30 ``` 这里假设你已经有了一个名为 Person 的 Java 类,其中包含名为 name 和 age 的属性。 ### 回答2: 使用JavaMap转换Java对象的步骤如下: 1. 首先,创建一个类,该类的属性应包含所有Map中的键。这些属性应与Map中的键具有相同的数据类型。 2. 在该类中,编写一个构造函数,该构造函数接受一个Map作为参数,并将Map中的值分配给类的相应属性。可以使用Map的get()方法来获取相应键的值,并使用setter方法将该值分配给类的属性。 3. 创建一个Map对象,该Map对象包含键和值的映射。可以使用HashMap或TreeMapMap的实现类。 4. 使用put()方法将键值对添加到Map对象中。 5. 创建类的实例,传递Map对象作为参数,将Map转换为类的对象。可以使用类的构造函数来完成此操作。 以下是一个示例代码: ```java import java.util.*; public class MapToObjectExample { private String name; private int age; // 构造函数 public MapToObjectExample(Map<String, Object> map) { this.name = (String) map.get("name"); this.age = (int) map.get("age"); } // getter和setter方法 public String getName() { return name; } public int getAge() { return age; } public static void main(String[] args) { // 创建Map对象 Map<String, Object> map = new HashMap<>(); map.put("name", "张三"); map.put("age", 25); // 将Map转换为对象 MapToObjectExample example = new MapToObjectExample(map); // 输出对象的属性值 System.out.println("姓名:" + example.getName()); System.out.println("年龄:" + example.getAge()); } } ``` 以上代码将Map对象转换为具有name和age属性的Java对象。在构造函数中,使用Map中的键来获取相应的值,并将其分配给类的属性。在main()方法中,创建Map对象,并将其传递给类的构造函数,实现将Map转换为对象的过程。最后,输出对象的属性值。 ### 回答3: 要将Map转换Java对象, 可以使用Java的反射机制和JavaBean规范来实现。 首先,我们需要定义一个Java类,该类的属性与Map中的键值对对应。例如,如果Map的键是"name",值是"John",那么我们需要在Java类中定义一个名为name的属性。 然后,我们可以使用Java的反射机制来创建该Java类的实例,并通过遍历Map中的键值对,将值赋给对应的属性。我们可以使用getClass()方法获取Java类的Class对象,再使用Class的newInstance()方法创建对象的实例。 接下来,我们可以使用反射的方式获取Java类中的属性,并使用属性的set方法将对应的值赋给该属性。 下面是一个简单的示例代码: ```java import java.lang.reflect.Field; import java.util.Map; public class MapToObjectConverter { public static <T> T convert(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException { T obj = clazz.newInstance(); for (Map.Entry<String, Object> entry : map.entrySet()) { String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); Field field = null; try { field = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { e.printStackTrace(); } if (field != null) { field.setAccessible(true); field.set(obj, fieldValue); } } return obj; } // 测试代码 public static void main(String[] args) { Map<String, Object> map = Map.of("name", "John", "age", 25); try { Person person = convert(map, Person.class); System.out.println(person.getName()); // 输出: John System.out.println(person.getAge()); // 输出: 25 } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); } } } class Person { private String name; private int age; // getter and setter methods // 省略 getter 和 setter 方法的实现 // ... } ``` 以上示例代码将Map中的"name"键对应的值赋给了Person类的name属性,将"age"键对应的值赋给了age属性。最后,我们可以通过调用相应的getter方法来获取对象的属性值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值