Peter Penzov
Peter Penzov

Reputation: 1668

Map Java DTO in response

I have a Java map which I would like to map using DTO in response. I tried this:

Service:

@Service
public class GatewaysService {

    public Map<Integer, String> getGatewaysList() {    
        Map<Integer, String> list = new HashMap<>();    
        list.put(1, "Bogus");    
        return list;
    }
}

API:

@Autowired
private GatewaysService gatewaysService;

    @GetMapping("gateways")
        public ResponseEntity<?> getGateways() {
            return ok(gatewaysService.getGatewaysList().map(mapper::toGatewayMap));
        }

DTO:

public class ContractGatewaysDTO {

    private Integer id;

    private String gateway;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getGateway() {
        return gateway;
    }

    public void setGateway(String gateway) {
        this.gateway = gateway;
    }
}

Mapper:

Map<Integer, String> toGatewayMap(ContractGatewaysDTO dto);

But I get error:

The method map(ContractDTO) in the type ContractsMapper is not applicable for the arguments (mapper::toGatewayMap)

What is the proper way to map it? I want to convert the Java map into key-value response.

Upvotes: 0

Views: 9130

Answers (2)

nortontgueno
nortontgueno

Reputation: 2791

What I was thinking is that you may want to convert the Map to the DTO entity, if it is what you need you can achieve by doing this:

return ResponseEntity.ok(getGatewaysList()
                                    .entrySet()
                                    .stream()
                                    .map( g -> new ContractGatewaysDTO(g.getKey(), g.getValue()))
                                    .collect(Collectors.toList()));

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32507

Why not just

@Autowired
private GatewaysService gatewaysService;

    @GetMapping("gateways")
        public Map<String,String> getGateways() {
            return gatewaysService.getGatewaysList();
        }

You dont have to map anything here.

Moreover

Unless in Java 9+ something changed, I don't recall java.uti.Map to have map method like you use it here

gatewaysService.getGatewaysList().map(mapper::toGatewayMap)

What i assume you tried to do is something like this:

List<Dto> yourlist= gatewaysService.getGatewaysList() //why MAP is named a LIST idk;
                        .entrySet() //can be any streamable collection - this comes with maps;
                        .stream()
                        .map(entry->new Dto(entry.key(),entry.value())
                        .collect(Collectors.toList());

Upvotes: 3

Related Questions