Map for DTO with stream spring boot

Viewed 550

I have question about map dto to key and value with stream in Spring Boot. I want create something like in example. Can you explain how I can do it without use Kryo framework and copy serialize instance?

For example Person is Set collection.

Person
.stream()
.collect(
toMap(PersonSet::Id, and value something like 'this' ));
3 Answers

If your Dto look like so :

public class Person {
    private Long id;
    //.. getter and setters
}

Then you can use toMap like so :

Set<Person> set = ...;
Map<Long, Person> result = set.stream()
        .collect(Collectors.toMap(Person::getId, Function.identity()));

I assume this is what you are looking for:

final Set<Person> personSet = //create a set of persons;
final Map<Integer, Person> personMap = personSet.stream().collect(Collectors.toMap(Person::id, person -> person).

Assuming Person::id is an integer - to create Map<Integer, Person> out of Set<Person> you can use something like :

Set<Person> people = ...

Map<Integer, Person> collect = people.stream()
          .collect(Collectors.toMap(Person::getId, Function.identity()));

using Collectors::toMap collector and Function::identity

Related