TryBeBetter
TryBeBetter

Reputation: 33

Map for DTO with stream spring boot

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' ));

Upvotes: 3

Views: 1032

Answers (3)

Artyom Rebrov
Artyom Rebrov

Reputation: 691

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).

Upvotes: 2

Michał Krzywański
Michał Krzywański

Reputation: 16920

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

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

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()));

Upvotes: 3

Related Questions