John Lennon
John Lennon

Reputation: 25

Creating a List of Maps from a List using java stream

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

Answers (2)

Ousmane D.
Ousmane D.

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

Youcef LAIDANI
Youcef LAIDANI

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

Related Questions