简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM