如何使用 Java 8 将 LinkedHashMap 列表转换为自定义对象列表

How can I convert List of LinkedHashMap to List of Custom Object using Java 8

我们如何使用 Java 8 个流将 List 转换为自定义对象列表 (List)。

示例:列表

这里的name和designation都是LinkedHashmap key。如果你在 IDE 中复制下面的片段,你可以更好地理解这个 List.

List<LinkedHashMap> list = new ArrayList<>();
LinkedHashMap<String, String> linkedHashMap1 = new LinkedHashMap<>((Map.of("name","David", "designation","Senior Software Engineer")));
LinkedHashMap<String, String> linkedHashMap2 = new LinkedHashMap<>((Map.of("name","Alex", "designation","Software Engineer")));
LinkedHashMap<String, String> linkedHashMap3 = new LinkedHashMap<>((Map.of("name","Jessi","designation","Lead")));
LinkedHashMap<String, String> linkedHashMap4 = new LinkedHashMap<>((Map.of("name","Martin","designation","Manager")));

list.add(linkedHashMap1);
list.add(linkedHashMap2);
list.add(linkedHashMap3);
list.add(linkedHashMap4);
System.out.println(list);

需要将上面的 List 转换为 List 其中 Employee class 有以下两个字段:

Class Employee {
String name;
String designation;
}

预期输出:

[Employee(name = David, designation = Senior Software Engineer), 
Employee(name = Alex, designation = Software Engineer), 
Employee(name = Jessi, designation = Lead),
Employee(name = Martin, designation = Manager)]      

使用流,您可以使用下面的代码,前提是您的 Employe class 具有带有此签名的构造函数:public Employe(String name, String designation).

List<Employe> customList= list.stream()
    .flatMap(map -> map.entrySet().stream())
    .map(entry -> new Employe(entry.getKey(), entry.getValue()))
    .toList();

在源列表上创建流。并使用映射到键 "name""designation".

的值将列表中的每个 map 转换为 Employee 的实例
public static void main(String[] args) {
    List<Map<String, String>> source = List.of(
            Map.of("name","David", "designation","Senior Software Engineer"),
            Map.of("name","Alex", "designation","Software Engineer"),
            Map.of("name","Jessi","designation","Lead"),
            Map.of("name","Martin","designation","Manager"));

    List<Employee> result = source.stream()
            .map(map -> new Employee(map.get("name"), map.get("designation")))
            .collect(Collectors.toList());

    result.forEach(System.out::println);
}

输出

Employee{name='David', designation='Senior Software Engineer'}
Employee{name='Alex', designation='Software Engineer'}
Employee{name='Jessi', designation='Lead'}
Employee{name='Martin', designation='Manager'}

注:

  • object 存储为 map 不是一个好习惯。在您的示例中,没有什么可以使您免于拼写错误,您将获得 null 而不是属性值。
  • 不要删除通用信息。