Skip to content
Advertisement

Lambda compareTo() not being recognized

@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StockDTO> findById(@PathVariable Long id){
    List<StockDTO> list = new ArrayList<>();
    StockDTO dto1= new StockDTO();
    dto1.setId(1L);
    dto1.setNameStock("AF");
    dto1.setPrice(100D);
    dto1.setVariation(10D);
    dto1.setDateStock(LocalDate.now());
    StockDTO dto2 = new StockDTO();
    dto2.setId(2L);
    dto2.setNameStock("AF2");
    dto2.setPrice(200D);
    dto2.setVariation(20D);
    dto2.setDateStock(LocalDate.now());
    list.add(dto1);
    list.add(dto2);

    StockDTO dtoSelect = list.stream().filter(x -> x.getId().compareTo(id)== 0).findFirst().get();
            return ResponseEntity.ok(dtoSelect);
}

I’m creating an endpoint to list just a single object with findById, and using lambda to go through the list and find the id, but the terminal is acusing an error because of the compareTo(id) part.

‘java: long cannot be dereferenced’

Need some help.

Advertisement

Answer

well id is long, so you should use == instead of .compareTo()

StockDTO dtoSelect = list.stream().filter(x -> x.getId() == id).findFirst().get();

Or “box” the id using Long.valueOf(id)

…btw, maybe you should use .equals() instead of .compareTo() == 0

Advertisement