2

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.

3
  • you can take reference from mkyong.com/java8/java-8-convert-list-to-map Commented Apr 18, 2018 at 13:19
  • Note : it seems that you actually want to convert your objects to JSON. There are libraries intended for that such as Jackson. Commented Apr 18, 2018 at 13:19
  • Indeed I want the output as JSON. But I'm bound to specific rules. Commented Apr 18, 2018 at 14:15

2 Answers 2

3

Java-9 solution using Map.of:

myList.stream()
      .map(s -> Map.of("name", s.getName(), "age", s.getAge()))
      .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

2

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}]

1 Comment

Thank you. This is exactly what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.