Reputation: 25
I have a List of Students that I want to convert to a List of Maps with each map containing specifc student data.
The Student Object:
class Student {
String name;
String age;
String getName() {
return name;
}
}
I have a list of Students that I want to convert to a list of maps that should look like the following:
[
{ name: "Mike",
age: "14"
},
{ name: "Jack",
age: "10"
},
{ name: "John",
age: "16"
},
{ name: "Paul",
age: "12"
}
]
Is there a way to convert List<Student>
into List<Map<String, String>>
? The keys of each map should be name & age.
Upvotes: 2
Views: 105
Reputation: 56393
Java-9 solution using Map.of
:
myList.stream()
.map(s -> Map.of("name", s.getName(), "age", s.getAge()))
.collect(Collectors.toList());
Upvotes: 3
Reputation: 59950
Did you mean :
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());
For example if you have :
List<Student> listStudent = new ArrayList<>(
Arrays.asList(
new Student("Mike", "14"),
new Student("Jack", "10"),
new Student("John", "16"),
new Student("Paul", "12")
));
The result should look like this :
[{name=Mike, age=14}, {name=Jack, age=10}, {name=John, age=16}, {name=Paul, age=12}]
Upvotes: 2