简体   繁体   中英

Transform Map<String, Object> to Object using Java streams

I have a Map<String, Object> and I want to transform it to an Object. Basically the Map will contain the following:

username xyz
password abc

I want to transform it to a SimpleUser object which has two fields: username and password. The current code looks like this, but I was wondering if I could do the object initialization inside the Stream:

Map<String, String> user = adapter
    .getSecret("abc")
    .orElseThrow()
    .entrySet().stream()
    .collect(Collectors.toMap(Entry::getKey, v -> v.getValue().toString()));

return new SimpleUser(user.get("username"), user.get("password"));

This is one not good pratice but tricky way to put them all in one line. Use jackson objectMapper only if the SimpleUser (Object) field names are the same as the Map, ie username and password.

SimpleUser u = new ObjectMapper().convertValue(
adapter.getSecret("abc")orElseThrow().entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, v -> v.getValue().toString()))
, SimpleUser.class);

And you will need this library.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>

For your reference.

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