【问题标题】:Creating a List of Maps from a List using java stream使用 java 流从列表创建地图列表
【发布时间】:2018-04-18 21:51:50
【问题描述】:

我有一个学生列表,我想将其转换为地图列表,其中每个地图都包含特定的学生数据。

学生对象:

class Student {
  String name;
  String age;

  String getName() {
    return name;
  }
}

我有一个学生列表,我想将其转换为如下所示的地图列表:

[
  { name: "Mike",
    age: "14"
  }, 
  { name: "Jack",
    age: "10"
  }, 
  { name: "John",
    age: "16"
  },
  { name: "Paul",
    age: "12"
  } 
]

有没有办法将 List<Student> 转换为 List<Map<String, String>> ?每个地图的键应该是姓名和年龄。

【问题讨论】:

  • 注意:您似乎真的想将您的对象转换为 JSON。有专门为此而设计的库,例如 Jackson。
  • 确实我希望输出为 JSON。但我必须遵守特定的规则。

标签: java data-structures java-8 java-stream


【解决方案1】:

使用Map.of的Java-9解决方案:

myList.stream()
      .map(s -> Map.of("name", s.getName(), "age", s.getAge()))
      .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    你的意思是:

    List<Student> listStudent = new ArrayList<>();
    List<Map<String, String>> result = listStudent.stream()
            .map(student -> {
                return new HashMap<String, String>() {
                    {
                        put("age", student.getAge());
                        put("name", student.getName());
                    }
                };
            }).collect(Collectors.toList());
    

    例如,如果您有:

    List<Student> listStudent = new ArrayList<>(
            Arrays.asList(
                    new Student("Mike", "14"),
                    new Student("Jack", "10"),
                    new Student("John", "16"),
                    new Student("Paul", "12")
            ));
    

    结果应该是这样的:

    [{name=Mike, age=14}, {name=Jack, age=10}, {name=John, age=16}, {name=Paul, age=12}]
    

    【讨论】:

    • 谢谢。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多